Friday, March 19, 2010

Read Data From a Excel Sheet , C# .NET

Reading data from a excel sheet is a simple task through the .NET. Following method will return a Data Table after reading the data from specified Sheet of the Excel sheet.
If you are going to select several columns from the sheet , then all the specifying column names needs to be map with the columns of the excel sheet. In the following example I just used the Select * (all).
Using any file uploading Control get the File Name and the Extension of the file.
  •  I have use the variable names strFileName, strExtension for File name and file extension respectively.
  • Sheet1 is the name of the excel sheet which is containing the required data in the specified Excel file
public DataTable ReadExcelToDataTable(string FileName, string Extention)
{
   string strConnectionString = string.Empty;
   if (Extention == "xls")//For Office 2003 version
   {
     strConnectionString =                     string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=   {0};Extended Properties=Excel 8.0", FileName);
   }
     else if (Extention=="xlsx")//for Office 2007
   {
    strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", FileName);
   }
     DataTable dttExecelDataTable = new DataTable();
     if (!string.IsNullOrEmpty(strConnectionString))
     {
         System.Data.OleDb.OleDbConnection objOleDBCon = new System.Data.OleDb.OleDbConnection(strConnectionString);
        try
        {
          objOleDBCon.Open(); // open excel file.
          System.Data.OleDb.OleDbCommand objDBCommand = new System.Data.OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", objOleDBCon);
          System.Data.OleDb.OleDbDataAdapter objOleAdapter = new System.Data.OleDb.OleDbDataAdapter (objDBCommand);
                    objOleAdapter.Fill(dttExecelDataTable);
        }
        catch (Exception)
        {
         throw;
        }
      }
    return dttExecelDataTable;

 }






No comments:

Post a Comment