Click here to Skip to main content
15,885,244 members
Articles / Web Development / ASP.NET
Tip/Trick

Load GridView from Excel

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
15 May 2013CPOL1 min read 28.1K   14   4
Loading Data from Excel

Introduction 

Hi everyone, here I am going to explain how to load data to a gridview or to a database from an Excel sheet. We need to load the data to the web application from external resources. 

Background 

I had seen many articles and searched google a lot of times. And i got the solution at last. What i am going to do is load the data to the gridview from Excel file. In many cases we need to load the data from external resources, so lets see that. 

My Excel file contains data like below. 

ID    FirstName    LastName
1      AAA          AAA
2      BBB          BBB
3      CCC          CCC  

Using the code 

First design the Excel sheet. For example i laod the excel sheet with columns ID, FirstName, LastName.  

XML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" 
            Height="21px" Text="Upload" 
            Width="92px" onclick="btnUpload_Click"/>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>  

The excel file can be uploaded using file upload control. Here I bind the Excel sheet data to a gridview. The code for the upload button will be, 

C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    String strConnection = "ConnectionString";
    string connectionString ="";
    if (FileUpload1.HasFile)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
        string fileLocation = Server.MapPath("~/App_Data/" + fileName);
        FileUpload1.SaveAs(fileLocation); 
        if (fileExtension == ".xls")
        {
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
              fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; 
        }
        else if (fileExtension == ".xlsx")
        {
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
              fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        } 
        OleDbConnection con = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
        DataTable dtExcelRecords = new DataTable();
        con.Open();
        DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
        cmd.CommandText = "SELECT * FROM [" + getExcelSheetName +"]";
        dAdapter.SelectCommand = cmd;
        dAdapter.Fill(dtExcelRecords); 
        GridView1.DataSource = dtExcelRecords;
        GridView1.DataBind(); 
    }

Points of Interest

If you want to store the data to the database. then use this code to copy the excel data to the database.  

C#
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnection))
{
  bulkCopy.ColumnMappings.Add("FirstName", "FirstName");
  bulkCopy.ColumnMappings.Add("LastName", "LastName"); 
  bulkCopy.DestinationTableName = "Excel_table";
  bulkCopy.WriteToServer(dtExcelRecords);
}

but make sure that the database contains table name  Excel_table with fields FirstName and LastName  

Conclusion

In many cases we need to load the data from external resources. In such cases we may use this. Hope its useful

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDownload Excel_Import.zip file missing Pin
Member 1175177014-Jun-15 19:10
Member 1175177014-Jun-15 19:10 
Questiongreat article Pin
Member 108135701-Jul-14 22:26
Member 108135701-Jul-14 22:26 
GeneralMy vote of 5 Pin
Member 108135701-Jul-14 22:23
Member 108135701-Jul-14 22:23 
QuestionImporting formatting from excel sheets Pin
jgdeveloper19-Jan-14 21:45
jgdeveloper19-Jan-14 21:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.