Read Excel File with .NET


Introduction
It is possible that we need to read Excel files when developing. In this article, I will show one method to read Excel file contents with .NET.
As is known, there are three types of Excel file.

  1. .xls format Office 2003 and the older version
  2. .xlsx format Office 2007 and the last version
  3. .csv format String text by separating with comma (the above two format can be saved as this format.)
We need to use different ways to read the first, second format files and the third format files.
Using the Code

Foreground
<div>
<span class="Apple-style-span" style="font-family: Arial,Helvetica,sans-serif;">
       <asp:fileupload id="fileSelect" runat="server">  
     
       <asp:button id="btnRead" runat="server" text="ReadStart">
</asp:button></asp:fileupload></span></div>

Background

//Declare Variable (property)
string currFilePath = string.Empty; //File Full Path
string currFileExtension = string.Empty;  //File Extension
 
//Page_Load Event, Register Button Click Event
 protected void Page_Load(object sender,EventArgs e)
 {
     this.btnRead.Click += new EventHandler(btnRead_Click);
 }
 
 //Button Click Event 
 protected void btnRead_Click(object sender,EventArgs e)
 {
     Upload();  //Upload File Method
     if(this.currFileExtension ==".xlsx" || this.currFileExtension ==".xls")
       {
            DataTable dt = ReadExcelToTable(currFilePath);  //Read Excel File (.XLS and .XLSX Format)
       }
     else if(this.currFileExtension == ".csv")
       {
           DataTable dt = ReadExcelWidthStream(currFilePath);  //Read .CSV File
       }
 }

The following shows three methods in button click event.

///Method to Read XLS/XLSX File
///
///Excel File Full Path///  private DataTable ReadExcelToTable(string path) {  //Connection String  string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";   // Extra blank space cannot appear in Office 2007 and the last version. And we need to pay attention on semicolon.  string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";  //This connection string is appropriate for Office 2007 and the older version. We can select the most suitable connection string according to Office version or our program.     using(OleDbConnection conn = new OleDbConnection(connstring))    {        conn.Open();        DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});  //Get All Sheets Name        string firstSheetName = sheetsName.Rows[0][2].ToString();   //Get the First Sheet Name        string sql = string.Format("SELECT * FROM [{0}],firstSheetName);  //Query String        OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);        DataSet set = new DataSet();        ada.Fill(set);        return set.Tables[0];       } } /// ///Method to Read CSV Format /// ///Read File Full Path///  private DataTable ReadExcelWithStream(string path) {    DataTable dt = new DataTable();    bool isDtHasColumn = false;   //Mark if DataTable Generates Column    StreamReader reader = new StreamReader(path,System.Text.Encoding.Default);  //Data Stream    while(!reader.EndOfStream)     {        string meaage = reader.ReadLine();        string[] splitResult = message.Split(new char[]{','},StringSplitOption.None);  //Read One Row and Separate by Comma, Save to Array        DataRow row = dt.NewRow();       {               if(!isDtHasColumn) //If not Generate Column                   {                         dt.Columns.Add("column" + i,typeof(string));                   }                     row[i] = splitResult[i];              }             dt.Rows.Add(row);  //Add Row             isDtHasColumn = true;  //Mark the Existed Column after Read the First Row, Not Generate Column after Reading Later Rows      }     return dt; } 
Read Excel File with .NET Read Excel File with .NET Reviewed by vishal on 7:37 AM Rating: 5