Here it is
This article will help you understand reading an excel file in C#. This
is often required when developing applications. Create an excel file
named "Test.xls" in the C Drive. The sample excel file will look like:
For interacting with an excel file you will have to include the following COM assemblies:
- Microsoft Excel 12.0 Object Library
- Microsoft Office 12.0 Object Library
Following code will be used to read the excel file and display the values in a Console application:
// Add Reference
using System;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
namespace ReadExcel
{
/// <summary>
/// This class will be used to read the excel and
/// display it in a console.
/// </summary>
class ReadExcelApplication
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// Path for the test excel application
string Path = @"c:\test.xls";
// Initialize the Excel Application class
Excel.ApplicationClass app = new ApplicationClass();
// Create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(Path,
0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
// Get the active worksheet using sheet name or active sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
int index = 1;
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while (((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
// Read the Cells to get the required value.
string firstName = ((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
index++;
rowIndex = index;
}
}
catch (Exception ex)
{
// Log the exception and quit...
app.Quit();
Console.WriteLine(ex.Message);
}
}
}
}
Hope this helps! Your comments are always welcome