Read and Import Excel File into DataSet or DataTable using C# in ASP.NET

1. Connection Strings

Since Excel 97-2003 and Excel 2007 use different providers I have placed two connection strings keys in the Web.Config.

  1. <connectionStrings>  
  2.   
  3.     <add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};  
  4.   
  5. Extended Properties='Excel 8.0;HDR={1}'" />  
  6.   
  7.     <add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};  
  8.   
  9. Extended Properties='Excel 8.0;HDR={1}'" />  
  10.   
  11. </connectionStrings>  

2. Front End design

The front end design of the web page contains a FileUpload Control, a button which will be used to upload the Excel File, RadioButtonList for the user to select whether headers are present or not by default Yes is selected and finally the GridView control in which I have set AllowPaging property to true.

  1. <asp:FileUpload ID="FileUpload1" runat="server" />  
  2.   
  3. <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
  4.   
  5. <br />  
  6.   
  7. <asp:Label ID="Label1" runat="server" Text="Has Header ?" />  
  8.   
  9. <asp:RadioButtonList ID="rbHDR" runat="server">  
  10.   
  11.     <asp:ListItem Text="Yes" Value="Yes" Selected="True">  
  12.   
  13.     </asp:ListItem>  
  14.   
  15.     <asp:ListItem Text="No" Value="No"></asp:ListItem>  
  16.   
  17. </asp:RadioButtonList>  
  18.   
  19. <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging="PageIndexChanging" AllowPaging="true">  
  20.   
  21. </asp:GridView>  
3. Uploading and Reading the Excel Sheet

Next comes the part to upload the file and read it. As you will notice in the aspx I have added OnClick event handler to the Upload button which will be triggered when the upload button is clicked

When the upload button is clicked the uploaded File is saved to a Folder whose path is defined in the App Settings section in the Web.Config using the following key

  1. <appSettings>  
  2.   
  3.     <add key="FolderPath" value="Files/" />  
  4.   
  5. </appSettings>  

4. Once the File is saved in the folder the Import_To_Grid method is called up which is described later. Below is the code snippet for the Upload button event handler

C#

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2.   
  3. {  
  4.   
  5.     if (FileUpload1.HasFile)  
  6.   
  7.     {  
  8.   
  9.         string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);  
  10.   
  11.         string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);  
  12.   
  13.         string FolderPath = ConfigurationManager.AppSettings["FolderPath"];  
  14.   
  15.         string FilePath = Server.MapPath(FolderPath + FileName);  
  16.   
  17.         FileUpload1.SaveAs(FilePath);  
  18.   
  19.         Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);  
  20.   
  21.     }  
  22.   
  23. }  

5. Now the saved Excel file is read using OLEDB. Based on the extension I decide the driver to be used in order to read the Excel file and also whether Excel will be read along with header row or not based on the RadioButtonList. All these values are filled in the placeholders of the connection string.

After that I read the schema of the Excel Workbook in order to find out the Sheet Name of the first sheet. Once I get that I fire a select query on the first Excel sheet and fill a datatable which is then passed to the GridView as data source. You can refer to the complete function below

C#

  1. private void Import_To_Grid(string FilePath, string Extension, string isHDR)  
  2.   
  3. {  
  4.   
  5.     string conStr = "";  
  6.   
  7.     switch (Extension)  
  8.   
  9.     {  
  10.   
  11.         case ".xls"//Excel 97-03  
  12.   
  13.             conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]  
  14.   
  15.             .ConnectionString;  
  16.   
  17.             break;  
  18.   
  19.         case ".xlsx"//Excel 07  
  20.   
  21.             conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]  
  22.   
  23.             .ConnectionString;  
  24.   
  25.             break;  
  26.   
  27.     }  
  28.   
  29.     conStr = String.Format(conStr, FilePath, isHDR);  
  30.   
  31.     OleDbConnection connExcel = new OleDbConnection(conStr);  
  32.   
  33.     OleDbCommand cmdExcel = new OleDbCommand();  
  34.   
  35.     OleDbDataAdapter oda = new OleDbDataAdapter();  
  36.   
  37.     DataTable dt = new DataTable();  
  38.   
  39.     cmdExcel.Connection = connExcel;  
  40.   
  41.     //Get the name of First Sheet  
  42.   
  43.     connExcel.Open();  
  44.   
  45.     DataTable dtExcelSchema;  
  46.   
  47.     dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  48.   
  49.     string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();  
  50.   
  51.     connExcel.Close();  
  52.   
  53.     //Read Data from First Sheet  
  54.   
  55.     connExcel.Open();  
  56.   
  57.     cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";  
  58.   
  59.     oda.SelectCommand = cmdExcel;  
  60.   
  61.     oda.Fill(dt);  
  62.   
  63.     connExcel.Close();  
  64.   
  65.     //Bind Data to GridView  
  66.   
  67.     GridView1.Caption = Path.GetFileName(FilePath);  
  68.   
  69.     GridView1.DataSource = dt;  
  70.   
  71.     GridView1.DataBind();  
  72.   
  73. }  

6. Pagination in GridView

Now in order to implement paging we will need to read the excel sheet each time and then rebind datatable to the GridView. Refer below

C#

  1. protected void PageIndexChanging(object sender, GridViewPageEventArgs e)  
  2.   
  3. {  
  4.   
  5.     string FolderPath = ConfigurationManager.AppSettings["FolderPath"];  
  6.   
  7.     string FileName = GridView1.Caption;  
  8.   
  9.     string Extension = Path.GetExtension(FileName);  
  10.   
  11.     string FilePath = Server.MapPath(FolderPath + FileName);  
  12.   
  13.     Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);  
  14.   
  15.     GridView1.PageIndex = e.NewPageIndex;  
  16.   
  17.     GridView1.DataBind();  
  18.   
  19. }  

Important thing to note is always close the connections after reading the Excel Workbook to avoid the following error, Server Error in 'ASP.Net' Application.

The process cannot access the file 'F:\ReadExcelToGrid\Files\Excel07.xlsx' because it is being used by another process.

Description:

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:

System.IO.IOException: The process cannot access the file 'F:\ReadExcelToGrid\Files\Excel07.xlsx' because it is being used by another process.

Ebook Download
View all
Learn
View all