How to Open and Read From Excel File in C#
First step is to add necessary references to the project.
1. Right click References and press Add References item in the menu.
2. Go to COM Tab and select Type Libraries.
3. Select the ticks of
- Microsoft Excel 14.0 Object Library
- Microsoft Office 14.0 Object Library
Required using statements:
using Microsoft.Office.Interop.Excel;
Here is the example code:
public void ReadExcelFile(String fileName)
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
var app = new Application();
var workbook = app.Workbooks.Open(path);
if (workbook.Sheets.Count > 0)
{
var worksheet = workbook.Sheets[1];
var range = worksheet.UsedRange;
var numRows = range.Rows.Count;
var numCols = range.Columns.Count;
for (int j = 1; j < numRows; ++j)
for (int i = 1; i < numCols; ++i)
if (range.Cells[j, i].Value2 != null)
var data = (Double.Parse(range.Cells[j, i].Value2.ToString()));
workbook.Close(true, null, null);
app.Quit();
ReleaseObject(worksheet);
ReleaseObject(workbook);
ReleaseObject(app);
}
}
private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Unable to release the Object {0}", ex.ToString());
}
finally
{
GC.Collect();
}
}
Contents related to 'How to Open and Read From Excel File in C#'
How to Create and Write Excel File in C#: How to create an excel file and write in its cells using c#?