Read an Excel file
The following code illustrates how to read an Excel file in C#.This code requires that the Office.dll & Microsoft.Office.Interop.Excel.dll files be added to the 'References' in the project.
The location of these files can vary. For Visual Studio 2013, they are in the folder "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15\".
For the application to run, Office (Excel) must be installed on the machine.
private void ReadExcel()
{
// declare a variable to hold the name of the Excel file to read
string sFileName = @"c:\myfile.xlsx";
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = null;
try
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
// open the workbook
xlWorkbook = xlApp.Workbooks.Open(sFileName);
// get the 1st worksheet in the workbook.
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
// get the range of cells used in the worksheet
Excel.Range range = xlWorksheet.UsedRange;
// Declare a loop to iterate thru the rows.
// Start with 2 to skip the first row. Top row is 1.
for (int lRowCnt = 2; lRowCnt <= range.Rows.Count; lRowCnt++)
{
// Iterate thru each of the columns, 1-based, not 0-based.
for (int lColCnt = 1; lColCnt < range.Columns.Count; lColCnt++)
{
// get a reference to the cell.
var cell = (range.Cells[lRowCnt, lColCnt] as Excel.Range);
// Do something with each row/cell value.
string sCellValue = (string)cell.Value2;
}
}
}
catch (Exception ex)
{
// handle any exceptions
}
finally
{
#region clean up
if (xlWorkbook != null)
{
xlWorkbook.Close(false);
}
if (xlApp != null)
{
xlApp.Quit();
}
ReleaseObject(xlWorksheet);
ReleaseObject(xlWorkbook);
ReleaseObject(xlApp);
#endregion
}
}
public static void ReleaseObject(object obj)
{
try
{
do
{
// nothing passed in? get out now.
if (obj null) break;
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
} while (false);
}
finally
{
GC.Collect();
}
}
Last modified by Mohit @ 4/5/2025 8:13:44 PM