Thursday, June 7, 2007

How to read an excel file using c# code

Suppose you have an excel file that contains the email , first name and last name values of some persons in the columns email, fname and lname


The following code snippet will read the file and return it in a dataset now you are free to use this dataset for your purpose

enjoy.....


private DataSet GetDetailsFromExcel()
{
Cursor.Current=Cursors.WaitCursor;

DataSet ds= new DataSet();
System.Data.DataTable dt = new System.Data.DataTable("list");
DataColumn dcol_email= new DataColumn("email");
DataColumn dcol_fname= new DataColumn("fname");
DataColumn dcol_lname= new DataColumn("lname");
dt.Columns.Add(dcol_email);
dt.Columns.Add(dcol_fname);
dt.Columns.Add(dcol_lname);
string Path = tbxFile.Text;
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;
int index = 1;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
object rowIndex = 2;
object colIndex1 = 1;
object colIndex2 = 2;
object colIndex3 = 3;

try
{
while ( ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2 != null )
{

string email = ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2.ToString();
string firstName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex2]).Value2.ToString();
string lastName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex3]).Value2.ToString();
DataRow dr = dt.NewRow();
dr["email"] = email;
dr["fname"] = firstName;
dr["lname"] = lastName;
dt.Rows.Add(dr);
rowIndex = 2+index;
index++;
}
}
catch(Exception ex)
{
app.Quit();
MessageBox.Show(ex.Message);
}
finally
{
app.Quit();

}
ds.Tables.Add(dt);
return ds;


}