ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Read and Import Excel Sheet into ASP.Net GridView Control
Author Name: Mudassar Khan Published Date: June 04, 2009
Filed Under :
ASP.Net
 |
Excel
 |
GridView
Views: 15628

In one of my articles I explained How to Read Excel using ADO.Net

In this article I am explaining: How to Read or Import Excel Sheet Data into ASP.Net GridView Control using OLEDB and ADO.Net.

 

Concept

1. User browses and selects an Excel Workbook.

2. User selects whether Header row is present in Excel Sheet or not using radio buttons.

3. User uploads the Excel Workbook

4. Uploaded File is read by the application and displayed on the web page using GridView Control.

5. GridView has paging enabled so that user can view the records easily.

 

Connection Strings

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

<connectionStrings>

  <add name ="Excel03ConString"

       connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};

                         Extended Properties='Excel 8.0;HDR={1}'"/>

  <add name ="Excel07ConString"

       connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};

                         Extended Properties='Excel 8.0;HDR={1}'"/>

</connectionStrings>

 

You will notice above there are two connection strings one for Excel 97 – 2003 format which uses Microsoft Jet driver and another one is for Excel 2007 format which uses Microsoft Ace driver.

I have used Placeholders for Data Source {0} and the HDR {1} property so that I can easily replace fill it in the front end based on the Excel File Selected and the Headers property selected by the user through the checkbox respectively

 

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.

 

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Text="Upload"

            OnClick="btnUpload_Click" />

<br />

<asp:Label ID="Label1" runat="server" Text="Has Header ?" />

<asp:RadioButtonList ID="rbHDR" runat="server">

    <asp:ListItem Text = "Yes" Value = "Yes" Selected = "True" >

    </asp:ListItem>

    <asp:ListItem Text = "No" Value = "No"></asp:ListItem>

</asp:RadioButtonList>

<asp:GridView ID="GridView1" runat="server"

OnPageIndexChanging = "PageIndexChanging" AllowPaging = "true">

</asp:GridView>

 

 

Uploading and Reading the Excel Sheet

Next comes the part to upload the file and reading 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

<appSettings>

  <add key ="FolderPath" value ="Files/"/>

</appSettings >

 

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#

protected void btnUpload_Click(object sender, EventArgs e)

{

    if (FileUpload1.HasFile)

    {

        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

        string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);

        string FolderPath = ConfigurationManager.AppSettings["FolderPath"];

 

        string FilePath = Server.MapPath(FolderPath + FileName);

        FileUpload1.SaveAs(FilePath);

        Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);

    }

}

 

 

VB.Net

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)

  If FileUpload1.HasFile Then

     Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)

     Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)

     Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")

 

     Dim FilePath As String = Server.MapPath(FolderPath + FileName)

     FileUpload1.SaveAs(FilePath)

     Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text)

  End If

End Sub

 

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 the complete function below

                              

 

 

C#

 

private void Import_To_Grid(string FilePath, string Extension, string isHDR)

{

    string conStr="";

    switch (Extension)

    {

        case ".xls": //Excel 97-03

            conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]

                     .ConnectionString;

            break;

        case ".xlsx": //Excel 07

            conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]

                      .ConnectionString;

            break;

    }

    conStr = String.Format(conStr, FilePath, isHDR);

    OleDbConnection connExcel = new OleDbConnection(conStr);

    OleDbCommand cmdExcel = new OleDbCommand();

    OleDbDataAdapter oda = new OleDbDataAdapter();

    DataTable dt = new DataTable();

    cmdExcel.Connection = connExcel;

 

    //Get the name of First Sheet

    connExcel.Open();

    DataTable dtExcelSchema;

    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

    connExcel.Close();

 

    //Read Data from First Sheet

    connExcel.Open();

    cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

    oda.SelectCommand = cmdExcel;

    oda.Fill(dt);

    connExcel.Close();

 

    //Bind Data to GridView

    GridView1.Caption = Path.GetFileName(FilePath);

    GridView1.DataSource = dt;

    GridView1.DataBind();

}

 

     

 

VB.Net

Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByVal isHDR As String)

  Dim conStr As String = ""

  Select Case Extension

      Case ".xls"

           'Excel 97-03

           conStr = ConfigurationManager.ConnectionStrings("Excel03ConString") _

                      .ConnectionString

           Exit Select

      Case ".xlsx"

           'Excel 07

            conStr = ConfigurationManager.ConnectionStrings("Excel07ConString") _

                      .ConnectionString

            Exit Select

  End Select

  conStr = String.Format(conStr, FilePath, isHDR)

 

  Dim connExcel As New OleDbConnection(conStr)

  Dim cmdExcel As New OleDbCommand()

  Dim oda As New OleDbDataAdapter()

  Dim dt As New DataTable()

 

  cmdExcel.Connection = connExcel

 

  'Get the name of First Sheet

  connExcel.Open()

  Dim dtExcelSchema As DataTable

  dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

  Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()

  connExcel.Close()

 

  'Read Data from First Sheet

   connExcel.Open()

   cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"

   oda.SelectCommand = cmdExcel

   oda.Fill(dt)

   connExcel.Close()

 

   'Bind Data to GridView

    GridView1.Caption = Path.GetFileName(FilePath)

    GridView1.DataSource = dt

    GridView1.DataBind()

End Sub

 

 

    

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#

protected void PageIndexChanging(object sender, GridViewPageEventArgs e)

{

    string FolderPath = ConfigurationManager.AppSettings["FolderPath"] ;

    string FileName = GridView1.Caption;

    string Extension = Path.GetExtension(FileName);

    string FilePath = Server.MapPath(FolderPath + FileName);

 

    Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text); 

    GridView1.PageIndex = e.NewPageIndex;

    GridView1.DataBind(); 

}

 

VB.Net

Protected Sub PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)

   Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")

   Dim FileName As String = GridView1.Caption

   Dim Extension As String = Path.GetExtension(FileName)

   Dim FilePath As String = Server.MapPath(FolderPath + FileName)

 

   Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text)

   GridView1.PageIndex = e.NewPageIndex

   GridView1.DataBind()

End Sub

 

The figure below displays the GridView populated from the excel workbook that is uploaded using the FileUpload Control.



Excel Sheet displayed in ASP.Net GridView control using ADO.Net


Important thing to note that 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.

 

You can download the source code in VB.Net and C# using the link below

ReadExcelToGrid.zip (37.83 kb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

BABA said:
Thank You for such usefull information.br it really works
February 12, 2010  

Smita said:
Very Good Article. I have found this useful
February 16, 2010  

Obiora said:
Nice one but How can I read the Header from the Excel file
March 17, 2010  

Mudassar Khan said:
Reply To: Obiora
Hi I have explained above both cases with Header and without header
March 18, 2010  

Senthil said:
Really a good article. Can you please tell me how to import the excel with its existing styles like bold images etc...
March 31, 2010  

Mudassar Khan said:
Reply To: Senthil
I don't think its possible to make bold and fetch images but in case you have image Urls you can fecth that from the cell and display in grid
March 31, 2010  

hmbreit said:
Thanks for your helpful article.br Can you please tell me how to deal with multiple users uploading excel-sheets with same schema but different content All users use the same Excel-sheet (same file-name). Do i have to provide a different file-name for each sheet beeing uploaded br I then create a pdf-report with iTextSharp and i do not want to save uploaded spreadsheets permanently on the webserver.br Thanks
April 13, 2010  

Mudassar Khan said:
Reply To: hmbreit
For different sheets you will need to pass the name of the sheet you want to read. For that you need to modify this line

cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"

and replace sheetname variable with the name of the sheet you want to read
April 14, 2010  

hmbreit said:
Im sorry my question was faulty.br My users load an excel template (report.xls) from the intranet to their workstations and key their data and save (filenamereport.xls). After having done this they upload it. The file is saved in the destination directory of the webserver. When another user is uploading the same file later on then report.xls gets overwritten by the later version isnt it I just need to databind the GridView and create a PDF using the GridViews content. After that I can delete the uploaded excel file on the webserver. But how can I make sure that each user has its own version of that excel file in the webservers destination directory And how can I delete processed filesbr Thanks
April 14, 2010  

Mudassar Khan said:
Reply To: hmbreit
2 ways
1. Store in different folder for each user
2. Rename it based on username or userid
April 14, 2010  

Richard Lemmon said:
Great article. Well explained. Thanks for posting
July 18, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code