简体   繁体   English

如何将数据从Excel工作表导入到SQL Server表中?

[英]how to import the data from excel sheet into sql server table?

Hi. 你好。 I want to import the excel sheet data to SQL server table,for that I wrote code like as below. 我想将Excel工作表数据导入SQL Server表,为此,我编写了如下代码。 The sheet is uploading into folder,but the data is not imported to table,can anyone tell me please where is the mistake.... 工作表正在上传到文件夹中,但是数据没有导入到表中,任何人都可以告诉我哪里出了错误。

public partial class upload2 : System.Web.UI.Page
    {
        private string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateDatabaseTables();
            }
        }

        private void PopulateDatabaseTables()
        {
            string tableName = string.Empty;
            string sql = "SELECT *, name AS table_name " +
                " FROM sys.tables WHERE Type = 'U' ORDER BY table_name";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (DataTable table = new DataTable())
                {
                    conn.Open();
                    using (SqlDataAdapter dAd = new SqlDataAdapter(sql, conn))
                    {
                        dAd.Fill(table);
                    }
                    ListBox1.DataSource = table;
                    ListBox1.DataBind();
                }
            }
        }

        protected void ImportNow_Click(object sender, EventArgs e)
        {
            if (ListBox1.SelectedValue == "")
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Please select table in which you want to import data from excel sheet";
            }
            else if ((fileuploadExcel.FileName != ""))
            {
                string extension = Path.GetExtension(fileuploadExcel.PostedFile.FileName);

                string excelConnectionString;
                SqlConnection conn = new SqlConnection(connStr);
                string tableName = ListBox1.SelectedValue;
               // string path = fileuploadExcel.PostedFile.FileName;
                string path = Server.MapPath("~/fileuploadExcel/" + fileuploadExcel.FileName);
                fileuploadExcel.SaveAs(path);
                Response.Write("path=" + path);
                return;
                //Create connection string to Excel work book
                if (extension == ".xlsx")
                {
                    excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=+ path +
                                                          ;Extended Properties=Excel 8.0;Persist Security Info=False";
                }
                else
                {
                    excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;sData Source= + path +
                                                         ;Extended Properties=Excel 12.0;Persist Security Info=False";
                }

                //Create Connection to Excel work book
                SqlConnection excelConnection = new SqlConnection(excelConnectionString);
                //Create OleDbCommand to fetch data from Excel             
                conn.Open();
                SqlCommand comm = new SqlCommand("truncate table " + tableName, conn);
                SqlCommand identityChange = conn.CreateCommand();
                identityChange.CommandText = "SET IDENTITY_INSERT " + tableName + " ON";
                SqlCommand cmd = new SqlCommand("Select * from [Sheet1$]", excelConnection);
                excelConnection.Open();
                SqlDataReader dReader;
                dReader = cmd.ExecuteReader();
                identityChange.ExecuteNonQuery();
                SqlBulkCopy sqlBulk = new SqlBulkCopy(connStr);
                //Give your Destination table name
                sqlBulk.DestinationTableName = tableName;
                sqlBulk.WriteToServer(dReader);
                excelConnection.Close();
                conn.Close();
                lblMessage.ForeColor = Color.Green;
                lblMessage.Text = "Import into table <b>" + tableName + "</b> successful!<br />";
            }
            else
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Please first upload (Select) excel file.";
            }
        }

        protected void viewdata_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            try
            {
                if (ListBox1.SelectedValue == "")
                {
                    lblMessage.ForeColor = Color.Red;
                    lblMessage.Text = "Please select table for which you want to view data in Gridview";
                }
                else
                {
                    string tableName = ListBox1.SelectedValue;
                    SqlConnection conn = new SqlConnection(connStr);
                    SqlDataAdapter sda = new SqlDataAdapter("select * from " + tableName, conn);
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    gvdetails.DataSource = ds;
                    gvdetails.DataBind();
                }
            }
            catch (DataException de)
            {
                lblMessage.Text = de.Message;
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvdetails.PageIndex = e.NewPageIndex;
            BindData();
        }
    }
}

excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= + path + ;Extended Properties=Excel 8.0;Persist Security Info=False"; excelConnectionString = @“ Provider = Microsoft.Jet.OLEDB.4.0; Data Source = + path + ;扩展属性= Excel 8.0; Persist Security Info = False”;

here you have directly used path , modify excelConnectionString as follows 在这里,您直接使用path ,如下修改excelConnectionString

excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}
                                                      ;Extended Properties=Excel 8.0;Persist Security Info=False",path);

Why dont you use MS SQL Server Import and Export Wizard.. it is easiest method ever. 为什么不使用MS SQL Server导入和导出向导..这是有史以来最简单的方法。

reffer this url and you can get exect idea. 引用此URL,您可以得到理想的主意。 Click Here to View 点击这里查看

Hope it helps you... 希望对您有帮助...

If you don't have Office installed on the server you may find it won't find the providers in your connection string... 如果服务器上未安装Office,则可能会在连接字符串中找不到提供者...

Provider=Microsoft.Jet.OLEDB.4.0;

Provider=Microsoft.ACE.OLEDB.12.0

Unfortunate but Microsoft never designed it to work without the server host paying extra to run Office on their server. 不幸的是,但是Microsoft从来没有将其设计为无法在服务器主机不支付额外费用才能在其服务器上运行Office的情况下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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