简体   繁体   中英

Read Excel Sheet Data and Bind With ASP.NET GridView

 protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
                FileUpload1.PostedFile.SaveAs(path);
                OleDbConnection oledbcon = new OleDbConnection("PROVIDER=MICROSOFT.ACE.OLEDB.12.0;DATA Source=" + path + ";Extended Properties=Excel 12.0;");
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [sheet1$]", oledbcon);
                OleDbDataAdapter ObjAdapter = new OleDbDataAdapter(cmd);
                oledbcon.Open();
                DbDataReader dr = cmd.ExecuteReader();
                string con_str = @"Data Source=RANGANATH;Initial Catalog=Ndexpress;Integrated Security=True";
                SqlBulkCopy bulkinsert = new SqlBulkCopy(con_str);
                bulkinsert.DestinationTableName = "deliveries";
                bulkinsert.WriteToServer(dr);
                oledbcon.Close();
                Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp"))), File.Delete);
                Label1.ForeColor = Color.Green;
                Label1.Text = "Succssfully Added";
                FetchData();

            }
        }

When this application run show this error-: {"The 'MICROSOFT.ACE.OLEDB.12.0' provider is not registered on the local machine."}

what is the solution?

try this.

string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(fuFile.PostedFile.FileName);
        fuFile.SaveAs(excelPath);

        string conString = string.Empty;
        string extension = Path.GetExtension(fuFile.PostedFile.FileName);
        switch (extension)
        {
            case ".xls": //Excel 97-03
                conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07 or higher
                conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;

        }
        conString = string.Format(conString, excelPath);
        using (OleDbConnection excel_con = new OleDbConnection(conString))
        {
            excel_con.Open();
            string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
            DataTable dtExcelData = new DataTable();

            //OPTIONAL
            dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Emp_Id", typeof(int)),
            new DataColumn("Emp_Name", typeof(string)),
            new DataColumn("Emp_Salary",typeof(decimal)) });

            using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
            {
                oda.Fill(dtExcelData);
            }
            excel_con.Close();

            string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(consString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    sqlBulkCopy.DestinationTableName = "dbo.tblEmps";

                    //OPTIONAL
                    sqlBulkCopy.ColumnMappings.Add("Emp_Id", "Emp_Number");
                    sqlBulkCopy.ColumnMappings.Add("Emp_Name", "Emp_Name");
                    sqlBulkCopy.ColumnMappings.Add("Emp_Salary", "Emp_Salary");
                    con.Open();
                    sqlBulkCopy.WriteToServer(dtExcelData);
                    con.Close();
                }
            }
        }

add this in web.config file

    <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM