How To Read An Excel File Using C#
How To Read An Excel File Using C#
about:reader?url=http://csharp.net-informations.com/excel/csharp-read-...
csharp.net-informations.com
1 of 4
27/06/2015 4:56
about:reader?url=http://csharp.net-informations.com/excel/csharp-read-...
excelSheet.Cells[3,3]);
How to get the range of occupied cells in excel sheet
For reading entire content of an Excel file in C#, we
have to know how many cells used in the Excel file.
In
order
to
find
the
used
range
we
use
2 of 4
27/06/2015 4:56
about:reader?url=http://csharp.net-informations.com/excel/csharp-read-...
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook =
xlApp.Workbooks.Open("csharp.netinformations.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);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <=
range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <=
range.Columns.Count; cCnt++)
{
str = (string)
(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
MessageBox.Show(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
3 of 4
27/06/2015 4:56
about:reader?url=http://csharp.net-informations.com/excel/csharp-read-...
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(ob
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to
release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
When you execute this C# source code the program read all used
cells from Excel file.
4 of 4
27/06/2015 4:56