如何将excel表中的数据导入到sql server表中?

Posted

技术标签:

【中文标题】如何将excel表中的数据导入到sql server表中?【英文标题】:how to import the data from excel sheet into sql server table? 【发布时间】:2013-10-16 08:12:56 【问题描述】:

嗨。我想将 Excel 工作表数据导入 SQL Server 表,为此我编写了如下代码。表格正在上传到文件夹,但数据没有导入表格,谁能告诉我错误在哪里......

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();
        
    

【问题讨论】:

LINQ to Excel 会省去不少麻烦。 code.google.com/p/linqtoexcel 【参考方案1】:

excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;数据源=+ path + ;Extended Properties=Excel 8.0;Persist Security Info=False";

这里你直接使用了path,修改excelConnectionString如下

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

【讨论】:

【参考方案2】:

为什么不使用 MS SQL Server 导入和导出向导.. 这是有史以来最简单的方法。

参考这个网址,你可以得到确切的想法。 Click Here to View

希望对你有帮助...

【讨论】:

我认为 OP 希望创建一个自动化进程/可执行文件来执行此任务。【参考方案3】:

如果您没有在服务器上安装 Office,您可能会发现它不会在您的连接字符串中找到提供程序...

Provider=Microsoft.Jet.OLEDB.4.0;

Provider=Microsoft.ACE.OLEDB.12.0

不幸的是,Microsoft 从未将其设计为无需服务器主机支付额外费用即可在其服务器上运行 Office。

【讨论】:

以上是关于如何将excel表中的数据导入到sql server表中?的主要内容,如果未能解决你的问题,请参考以下文章

如何将SQL Server中多个表的数据一次性返回到一张EXCEL工作表(Sheet)中

怎样将EXCEL数据表导入到SQL中

ASP.NET中如何将Excel表中的数据导入到数据库中?

用JAVA快速的将一个表中的数据导入到另一个表里

如何将excel文件导入到一个oracle表中?谢谢

如何将excel中的数据导入hive仓库中