Skip to content

Instantly share code, notes, and snippets.

@abhi1010
Last active August 29, 2015 14:01
Show Gist options
  • Save abhi1010/ee13f57720471c8feea2 to your computer and use it in GitHub Desktop.
Save abhi1010/ee13f57720471c8feea2 to your computer and use it in GitHub Desktop.
Read Excel in C#
public static void readExcelFile(string fileLocation, int workbookIndex, int worksheetIndex)
{
// First open the Excel file
Application excelApp = default(Application);
excelApp = new Application();
excelApp.Workbooks.Open(fileLocation);
// WorkBooks can be counted by using excelApp.Workbooks.Count
// To find out how many worksheets are there, on index 'workbookIndex' use the following:
// - excelApp.Workbooks[workbookIndex].Worksheets.Count
// If you want to print out the WorkSheet names
foreach (Worksheet ws in excelApp.Workbooks[workbookIndex].Worksheets)
{
Console.WriteLine("worksheet = " + ws.Name);
}
// Pick out the Worksheet that you wanted
Worksheet xlWorkSheet = excelApp.Workbooks[workbookIndex].Worksheets[worksheetIndex];
xlWorkSheet.Select();
// Find out the Range of cells that were used in Specified worksheet
// Possible bug in this though, if you add more columns after the first used row - this number may be wrong
Range range = xlWorkSheet.UsedRange;
// Assuming data starts from row #0.
for (int rowCounter = 0; rowCounter <= range.Rows.Count; rowCounter++)
{
for (int columnCounter = 0; columnCounter <= range.Columns.Count; columnCounter++)
{
// If you are using special data types like string and the cell contains other types like 'double'
// then you may get exceptions while type casting - just something to be aware of
// You may also get exception if data doesnt start from row 0
dynamic val = range.Cells[rowCounter, columnCounter].Value;
// Make sure it actually has some data
if (val != null && val.ToString().Length > 0)
{
Console.WriteLine("Value=" + val.ToString() + ", ");
}
}
}
excelApp.Workbooks[workbookIndex].Close(false);
excelApp.Quit();
excelApp = null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment