Load an Excel file using implicit typing - c#

class ExcelHandling
{
public static void NewExcelFile(){
frmMain._frmMain.EXCEL_FILE = new Excel.Application();
var excelApp = frmMain._frmMain.EXCEL_FILE as Excel.Application;
excelApp.Workbooks.Add();
excelApp.Visible = true;
}
public static void LoadExcelFile()
{
FileStream load = File.Open(#"F:\dsa.xlsx", FileMode.Open, FileAccess.Write);
var excelApp = load as Excel.Application;
frmMain._frmMain.EXCEL_FILE = excelApp;
excelApp.Visible = true;
}
}
The above shown LoadExcelFile() method doesn't work.
What is the correct way of loading an existing excel file into a variable? I've tried a few things, but to no avail. The NewExcelFile() method works like a charm - it creates a new Excel file, stores it into the EXCEL_FILE global variable so I can manipulate it thereafter and shows it. I want the load function to do the same but with an existing excel file.

Here is an example of opening an existing Excel spreadsheet using the Microsoft.Interop library:
var xlApp = new Microsoft.Office.Interop.Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open("PathAndNameOfMyFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
The overload parameters are fairly vague in documentation, but unfortunately required. Intellisense should give you some idea of the values and their meaning.
Your issue was that you were using a FileStream and then trying to let the library figure out what that stream contained. This will utilize the interop library to open the file and handle the data properly.

I really like LinqToExcel. You can use NuGet Package Mgr in Visual Studio to add it https://www.nuget.org/packages/LinqToExcel . Documentation is #https://code.google.com/p/linqtoexcel/ (with a demo video)

Related

How to open an Excel file in PrintPreview without suspending the code

I'm new to C#/OpenXML and could not find an answer to this. Apologies in advance if it's a stupid question...
Basically, I am writing an application that creates Excel files from an input string. This input string may contain information about multiple files that need to be created and opened in the print preview dialog simultaneously. However, using the following function, the code is suspended on the printpreview.show() method as it waits for the user to close the preview.
public static void ExcelOpen(string fileName)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, false, 0, false, false);
Excel.Worksheet ws = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrintPreview].Show();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
return;
}
How can I avoid this and make sure the window stays opened in print preview but my program continues to run and create/display further files?

Returning Excel variables C#

I have a Windows Forms application with 5 methods (each based off of the user clicking a button). In each method, I would like to open the same excel file the same way. However, in each method I want to select a different range on the worksheet. I tried creating a function to open the excel file rather than rewriting it 5 times...
// method to open Excel and load a the workbook based on date selected.
public Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> openExcel()
{
Microsoft.Office.Interop.Excel.Application excelObj = new Microsoft.Office.Interop.Excel.Application();
string fileName = #"C:\Users\" + userName + #"\Documents\Visual Studio 2015\Projects\ProgramForMom\ProgramForMom\bin\Debug\Excel Files\" + frm2.year.Text + " Expenses";
Workbook wb = excelObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
wb.Activate(); // Activates file.
Worksheet ws = wb.Worksheets[frm2.month.Text];
ws.Activate();
return Tuple.Create(excelObj, wb, ws);
}
All that works fine.
I tried referenced this function in one of the methods...
var excelObj = openExcel();
Workbook wb = openExcel();
Worksheet ws = openExcel();
var cellValue = ws.Range["A1"].Value2;
and I get an error saying...
"Cannot implicitly convert type 'System.Tuple' to 'Microsoft.Office.Interop.Excel.Workbook'. An explicit conversion exists (are you missing a cast?)"
I get the same error for the worksheet. It says the same exact thing just substitutes the word worksheet in place of workbook.
Can you please explain what I have done wrong? Thank you.
var result = openExcel();
var excelObj = result.Item1;
Workbook wb = result.Item2;
Worksheet ws = result.Item3;
var cellValue = ws.Range["A1"].Value2;
You have a mismatch between the return type of your method (which is a Tuple) and the type of the variables in which you want to catch the output of openExcel
it should look more like this
Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> allThreeInOne = openExcell();
then you can try and fiddle everything apart... OR
what you also can do is to access the value right at the point of the function call:
var excelObj = openExcel().Item1;
Workbook wb = openExcel().Item2;
Worksheet ws = openExcel().Item3;
this way you would assign exactly the matching type to the variables
EDIT:
Tha latter solution is not advisable since you would unnecessarily open the file 3 times just to get the result that you would have gotten already from the first call,as Joel Coehoorn correctly pointed out.
fiddling the tuple apart would be the way to go:
var excelObj = allThreeInOne.Item1;
Workbook wb = allThreeInOne.Item2;
Worksheet ws = allThreeInOne.Item3;

Workbooks.Open vs OLEDBConnection fails to open workbook

I'm getting error:
Excel cannot open the file 'FILE.xlsx' because the file format or
file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file.
I suspect the reason is due to the fact that on File.xlsx I have a OleDBConnection using it and that later in the same code I call the Interop function Open of Excel on that file. Can someone confirm my theory?
public ExcelWorkbook(string file)
{
fileName = file;
using (var workbookConnection = new OleDbConnection(String.Format(Resource.ExcelConnectionString, file)))
{
workbookConnection.Open();
tabNames = GetDataTabsName(workbookConnection);
foreach (string tabName in tabNames)
{
var newExcelTab = new ExcelTab(workbookConnection, file, tabName);
excelTabs.Add(tabName, newExcelTab);
}
}
}
Then my function GetDataTabsName(workbookConnection);
private List<string> GetDataTabsName(OleDbConnection workbookConnection)
{
var tabsName = new List<string>();
var tabName = "";
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
Excel.Workbook workbook = excelApp.Workbooks.Open(workbookConnection.DataSource, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
....some more code
The Open fails here...and my best guess is that because an OleDBConnection is exist on that file??
After further testing, it turned out that my guess was right. So having an OleDBConnection open on a worksheet cannot be opened simultaneously with Microsoft.InterOp
The third parameter to Workbooks.Open specifies whether or not the work should be opened in read-only mode. If the interop connection is only for reading, try setting that value to true. If the OleDb connection can be read-only, add ReadOnly=true; to your connection string.

how to identify that a worksheet is minimized?

How to identify the current active worksheet is minimized ?
I do not want to run my operation when the current worksheet in excel is minimized. I am using excel interop and C#
You can do a conditional check on the following property,
If Application.WindowState = xlMinimized Then
// do something
End If
This is in VBA though.
Here is a basic code in C#
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application myXL = new Excel.Application();
myXL.Visible = true;
//adding a new book
Excel.Workbook xlBookN = myXL.Workbooks.Add();
//opening exising book
String xlPath = "c:/myprojects/test.xls";
Excel.Workbook xlBookE = myXL.Workbooks.Open(xlPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Dim myWindowState As XlWindowState //you could also use a variable
myXL.WindowState = myWindowState
//or you can check the state directly
If (myXL.WindowState = xlMinimized)
// do something
End If
Please check on the syntax and references.
You could get better reference from :
MSDN
MSDN OFFICE INTEROP

How to open an Excel file in C#?

I am trying to convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work?
Excel.Application objexcel;
Excel.Workbook wbexcel;
bool wbexists;
Excel.Worksheet objsht;
Excel.Range objrange;
objexcel = new Excel.Application();
if (Directory("C:\\csharp\\error report1.xls") = "")
{
wbexcel.NewSheet();
}
else
{
wbexcel.Open("C:\\csharp\\error report1.xls");
objsht = ("sheet1");
}
objsht.Activate();
You need to have installed Microsoft Visual Studio Tools for Office (VSTO).
VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.
After that create a generic .NET project and add a reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value is a special reflection struct for unnecessary parameters replacement
In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.
FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
System.Diagnostics.Process.Start(#"C:\test\report.xlsx");
}
else
{
//file doesn't exist
}
private void btnChoose2_Click(object sender, EventArgs e)
{
OpenFileDialog openfileDialog1 = new OpenFileDialog();
if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.btnChoose2.Text = openfileDialog1.FileName;
String filename = DialogResult.ToString();
var excelApp = new Excel.Application();
excelApp.Visible = true;
excelApp.Workbooks.Open(btnChoose2.Text);
}
}
Imports
using Excel= Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
Here is the code to open an excel sheet using C#.
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
wbv.Close(true, Type.Missing, Type.Missing);
excel.Quit();
Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4
For opening a file, try this:
objexcel.Workbooks.Open(#"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
you should open like this
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
source : http://csharp.net-informations.com/excel/csharp-open-excel.htm
ruden
It's easier to help you if you say what's wrong as well, or what fails when you run it.
But from a quick glance you've confused a few things.
The following doesn't work because of a couple of issues.
if (Directory("C:\\csharp\\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
What you should do (for this line at least) is the following
FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
Microsoft.Office.Interop.Excel.Application excapp;
excapp = new Microsoft.Office.Interop.Excel.Application();
object misval=System.Reflection.Missing.Value;
Workbook wrkbuk = new Workbook();
Worksheet wrksht = new Worksheet();
wrkbuk = excapp.Workbooks._Open(#"C:\Users\...\..._template_v1.0.xlsx", misval, misval,
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);
wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);
Is this a commercial application or some hobbyist / open source software?
I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.
But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.
Code :
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled=false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excell File |*.xlsx;*,xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
string extn = Path.GetExtension(ofd.FileName);
if (extn.Equals(".xls") || extn.Equals(".xlsx"))
{
filename = ofd.FileName;
if (filename != "")
{
try
{
string excelfilename = Path.GetFileName(filename);
}
catch (Exception ew)
{
MessageBox.Show("Errror:" + ew.ToString());
}
}
}
}
For editing Excel files from within a C# application, I recently started using NPOI.
I'm very satisfied with it.

Categories