How to open an Excel file in C#? - 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.

Related

Exception thrown while closing Excel

Morning,
I am writing simple windows service that will take excel file from given location, generate xml file and move excel to another folder.
I am using:
Excel = Microsoft.Office.Interop.Excel
My code looks like this:
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
try
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(file);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Części");
//doing something with xml and excel
xlApp.DisplayAlerts = false;
xlWorkBook.Close();
xlApp.Quit();
} catch (Exception e) {
this.writeErrorLog(e);
} finally {
// Close the Excel process
if (null != xlWorkSheet)
Marshal.ReleaseComObject(xlWorkSheet);
if (null != xlWorkBook)
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
GC.Collect();
}
My problem is that when i run it as normal program it works fine and does everything i need. But when i create service and install it, it creates exceptions every time i upload excel file to this folder. Exception says that program could not gain access to my excel file.
System.Runtime.InteropServices.COMException
I have checked this topic but it didn't help me. Can anyone help me solve this problem?
EDIT: Btw. I am using this tutorial to create service.
EDITv2: The way i take file paths:
string sc_path = #"C:\Projekty\AAPLXML\AppFolders\upload";
string tg_path = #"C:\Projekty\AAPLXML\AppFolders\processed";
if (System.IO.Directory.Exists(sc_path) && System.IO.Directory.Exists(tg_path))
{
List<string> files = System.IO.Directory.GetFiles(sc_path).ToList();
if (files.Count == 0) return;
files.ForEach(f => new XmlGenerator(f).Start());
}

Opening Excel workbook via code vs dbl clicking

I have an excel file that runs some simulation. It's too complex to post here but it's also not the thing really in question, but what I'm seeing is that if I just dbl click the workbook to open it and then run the simulation (click a button on the workbook) it works fine. However if I use the below code in a C# project to open the workbook and then run the simulation (again just click the button) it gives different results. I'm wondering if anyone knows anything about why anything would be different when you open a workbook via code vs just dbl clicking it to open. I'm completely at a loss and any ideas at all would help a ton. Thanks!
private Application oExcel = null;
private Workbooks oBooks = null;
private _Workbook oBook = null;
private void OpenExcelFile(string filename)
{
oExcel = new Application();
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
//oExcel.DisplayAlerts = true;
oBooks = oExcel.Workbooks;
oBook = oBooks.Open(filename);
}
I've tried both Microsoft Excel 14.0 and 15.0 Object Library

Load an Excel file using implicit typing

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)

how to read the value from excel in c# without using third party dll?

I have a excel file which is named strings.xls in C:
Excel.Application excelApp = new Excel.Application();
string workbookPath = "c:/strings.xls";
Excel.Workbook excelWorkbook = null;
try
{
excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
}
catch
{
excelWorkbook = excelApp.Workbooks.Add();
}
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A1", "A1");
excelCell.Value2 = "Hi There";
You can't.
Since this is XLS file (a binary format), the simplest solution would be to use Excel (Microsoft Jet) OLE DB driver to retrieve that value. Example
If you can change the process to provide XLSX files then you could open then in plain .NET and parse the values out of the XML files.
You can use Jet OLE DB Provider With Microsoft Excel Workbooks to read values from excel. This is good codeproject article with example code for oledb with excel.
You can also use do it using Microsoft.Office.Interop.Excel, this codeproject article would be good starting point.
You can connect to an Excel file using OLE DB provider.
Have a look at this example.

Export data from dataset to excel

I am trying to export data from dataset to excel and save it directly to a given path without giving me the option to open,save or cancel.
Using ExcelLibrary this is a one liner ...
DataSet myDataSet;
... populate data set ...
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", myDataSet);
See also Create Excel (.XLS and .XLSX) file from C#
This C# Excel library can also be used to export the dataset. More details about how to export can be found here.
ExcelDocument xls = new ExcelDocument();
xls.easy_WriteXLSFile_FromDataSet("ExcelFile.xls", dataset,
new ExcelAutoFormat(Styles.AUTOFORMAT_EASYXLS1), "Sheet Name");
It's not the greatest solution but here is what I did, it opens a new excel document then copies what is in the dataset, all you need to do is sort out the columns and save it.
Btw totes my first post to answer a question, hope it helps
private void cmdExport_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("excel.exe");
try
{
copyAlltoClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
private void copyAlltoClipboard()
{
dataGridViewItems.SelectAll();
DataObject dataObj = dataGridViewItems.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
Check this DataSetToExcel
and c# (WinForms-App) export DataSet to Excel
In the first link change the code as follows:
Remove the all code that initially starts and try the following
using (StringWriter sw = new StringWriter("Your Path to save"))
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
}
}
Here's another C# library, which lets you export from a DataSet to an Excel 2007 .xlsx file, using the OpenXML libraries.
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
All of the source code is provided, free of charge, along with a demo application, and you can use this in your ASP.Net, WPF and WinForms applications.
Once you've added the class to your application, it just takes one function call to export your data into an Excel file.
CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");
It doesn't get much easier than that.
Good luck !
Hi i found a perfect solution Here
Just replace 'missing.value' with System.Type.Missing in the code. Also remove
oWB.Close(System.Type.Missing, System.Type.Missing, System.Type.Missing);
and
oXL.Quit();
from the code. Otherwise your excel will get closed automatically as soon as it open.

Categories