如何导入 xls 并将行分配给表列?

Posted

技术标签:

【中文标题】如何导入 xls 并将行分配给表列?【英文标题】:How to import xls with assigning row to to table column? 【发布时间】:2014-06-05 12:28:48 【问题描述】:

我只想做一个xls列映射功能,以便用户可以直接将xls数据导入sql。这是我的代码:

在这里我必须分配用户输入的行号。从文本框中分配每个目标列的更好方法是什么。有什么身体可以帮助我吗?

更新

我刚刚编写了新代码,但这次运气不佳,我发现了一些未找到的列异常。

 protected void lbut_import_Click(object sender, EventArgs e)
    
        if (FileUpload1.HasFile)
            
                if (FileUpload1.FileContent.Length > 0)
                
                    string Foldername;
                    string Extension = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
                    string filename = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                    if (Extension == ".XLS" || Extension == ".XLSX" || Extension == ".xls" || Extension == ".xlsx")
                    
                        Foldername = Server.MapPath("~/Files/");
                        FileUpload1.PostedFile.SaveAs(Foldername + filename + Extension);
                        string conString = string.Empty;
                        switch (Extension)
                        
                            case ".xls": //Excel 97-03
                                conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                                break;

                            case ".xlsx": //Excel 07
                              conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
                                break;
                        
                        conString = string.Format(conString, Foldername + filename + Extension);

                        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]: It is recommended as otherwise the data will be considered as String by default.
                            dtExcelData.Columns.AddRange(new DataColumn[23] 
                                                        new DataColumn("Name", typeof(string)),
                                                         new DataColumn("type_id", typeof(int)),
                                                         new DataColumn("Ownername",typeof(string)),
                                                         new DataColumn("Ownermob",typeof(string)),
                                                         new DataColumn("Room",typeof(string)),
                                                         new DataColumn("Build",typeof(string)),
                                                         new DataColumn("Road",typeof(string)),
                                                         new DataColumn("Area",typeof(string)),
                                                         new DataColumn("City",typeof(string)),
                                                         new DataColumn("Phone",typeof(string)),
                                                         new DataColumn("Mobile",typeof(string)),
                                                         new DataColumn("Email",typeof(string)),
                                                         new DataColumn("ContactPerson",typeof(string)),
                                                         new DataColumn("ContactPersonmob",typeof(string)),
                                                         new DataColumn("UserOFC",typeof(bool)),
                                                         new DataColumn("UserVAT",typeof(bool)),
                                                         new DataColumn("UserINV",typeof(bool)),
                                                         new DataColumn("UserNone",typeof(bool)),
                                                         new DataColumn("state_id",typeof(int)),
                                                         new DataColumn("country_id",typeof(int)),
                                                         new DataColumn("Remark",typeof(string)),
                                                         new DataColumn("Register_Date",typeof(DateTime)),
                                                         new DataColumn("User_id",typeof(string)),
                                                        );

                            using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
                            
                                oda.Fill(dtExcelData);
                            
                            excel_con.Close();
                            string consString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ToString();
                            using (SqlConnection con = new SqlConnection(consString))
                            
                                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                                
                                    //Set the database table name
                                    sqlBulkCopy.DestinationTableName = "tbl_Party_master";

                                    //[OPTIONAL]: Map the Excel columns with that of the database table
                                    sqlBulkCopy.ColumnMappings.Add("Name", dtExcelData.Columns[int.Parse(txt_col.Text.Trim())].ToString());
                                    sqlBulkCopy.ColumnMappings.Add("type_id",dtExcelData.Columns[int.Parse(txt_col1.Text.Trim())].ToString());
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col2.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Ownername",dtExcelData.Columns[int.Parse(txt_col2.Text.Trim())].ToString());
                                    
                                    if (!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col3.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Ownermob", dtExcelData.Columns[int.Parse(txt_col3.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col4.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Room",dtExcelData.Columns[int.Parse(txt_col4.Text.Trim())].ToString());
                                    
                                    if (!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col5.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Build", dtExcelData.Columns[int.Parse(txt_col5.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col6.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Road",dtExcelData.Columns[int.Parse(txt_col6.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col7.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Area",dtExcelData.Columns[int.Parse(txt_col7.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col8.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("City",dtExcelData.Columns[int.Parse(txt_col8.Text.Trim())].ToString());
                                    
                                    if (!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col9.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Phone", dtExcelData.Columns[int.Parse(txt_col9.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col10.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Mobile",dtExcelData.Columns[int.Parse(txt_col10.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col11.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Email",dtExcelData.Columns[int.Parse(txt_col11.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col12.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("ContactPerson",dtExcelData.Columns[int.Parse(txt_col12.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col13.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("ContactPersonmob", dtExcelData.Columns[int.Parse(txt_col13.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col14.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("UserOFC", dtExcelData.Columns[int.Parse(txt_col14.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col15.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("UserVAT",dtExcelData.Columns[int.Parse(txt_col15.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col16.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("UserINV",dtExcelData.Columns[int.Parse(txt_col16.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col17.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("UserNone",dtExcelData.Columns[int.Parse(txt_col17.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col18.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("state_id",dtExcelData.Columns[int.Parse(txt_col18.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col19.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("country_id",dtExcelData.Columns[int.Parse(txt_col19.Text.Trim())].ToString());
                                    
                                    if(!string.IsNullOrEmpty(dtExcelData.Columns[int.Parse(txt_col20.Text.Trim())].ToString()))
                                    
                                        sqlBulkCopy.ColumnMappings.Add("Remark",dtExcelData.Columns[int.Parse(txt_col20.Text.Trim())].ToString());
                                    
                                    sqlBulkCopy.ColumnMappings.Add("Register_Date",dtExcelData.Columns[int.Parse(txt_col21.Text.Trim())].ToString());
                                    sqlBulkCopy.ColumnMappings.Add("User_id",dtExcelData.Columns[int.Parse(txt_col22.Text.Trim())].ToString());
                                    con.Open();
                                    sqlBulkCopy.WriteToServer(dtExcelData);
                                    con.Close();
                                
                            
                            StringBuilder sb = new StringBuilder();
                            sb.Append("<script type = 'text/javascript'>");
                            sb.Append("alert('");
                            sb.Append(dtExcelData.Rows.Count.ToString());
                            sb.Append(" Rows(s) are Inserted.');");
                            sb.Append("</script>");
                            ClientScript.RegisterStartupScript(this.GetType(), "script", sb.ToString());
                        
                    
                
                ibtnimexls_ModalPopupExtender.Show();
            
    

从列映射的最后一行我发现如下错误:

Server Error in '/CRM' Application.

Cannot find column 23.

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.IndexOutOfRangeException: Cannot find column 23.

Source Error: 


Line 3403:                                    
Line 3404:                                    sqlBulkCopy.ColumnMappings.Add("Register_Date",dtExcelData.Columns[int.Parse(txt_col21.Text.Trim())].ToString());
Line 3405:                                    sqlBulkCopy.ColumnMappings.Add("User_id",dtExcelData.Columns[int.Parse(txt_col22.Text.Trim())].ToString());
Line 3406:                                    con.Open();
Line 3407:                                    sqlBulkCopy.WriteToServer(dtExcelData);

Source File: f:\CRM\Staff\Raise_Ticket.aspx.cs    Line: 3405 

Stack Trace: 


[IndexOutOfRangeException: Cannot find column 23.]
   System.Data.DataColumnCollection.get_Item(Int32 index) +95
   Staff_Raise_Ticket.lbut_import_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:3405
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

更新

Column 'Name' does not allow DBNull.Value.

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.InvalidOperationException: Column 'Name' does not allow DBNull.Value.

Source Error: 


Line 3407:                                    sqlBulkCopy.ColumnMappings.Add("Register_Date", dtExcelData.Columns[int.Parse(txt_col21.Text.Trim())].ToString());
Line 3408:                                    sqlBulkCopy.ColumnMappings.Add("User_id", dtExcelData.Columns[int.Parse(txt_col22.Text.Trim())].ToString());
Line 3409:                                    sqlBulkCopy.WriteToServer(dtExcelData);
Line 3410:                                    con.Close();
Line 3411:                                

Source File: f:\CRM\Staff\Raise_Ticket.aspx.cs    Line: 3409 

Stack Trace: 


[InvalidOperationException: Column 'Name' does not allow DBNull.Value.]
   System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata) +953277
   System.Data.SqlClient.SqlBulkCopy.WriteToServerInternal() +1393
   System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServer(Int32 columnCount) +762
   System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table, DataRowState rowState) +186
   System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table) +6
   Staff_Raise_Ticket.lbut_import_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:3409
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

【问题讨论】:

你的“dReader = cmd.ExecuteReader();”获取填充值? 【参考方案1】:

你可以试试这个:

protected void Upload(object sender, EventArgs e)

    //Upload and save the file
    string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
    FileUpload1.SaveAs(excelPath);

    string conString = string.Empty;
    string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
    switch (extension)
    
        case ".xls": //Excel 97-03
            conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
            break;
        case ".xlsx": //Excel 07 or higher
            conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].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]: It is recommended as otherwise the data will be considered as String by default.
        dtExcelData.Columns.AddRange(new DataColumn[3]  new DataColumn("Id", typeof(int)),
                new DataColumn("Name", typeof(string)),
                new DataColumn("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))
            
                //Set the database table name
                sqlBulkCopy.DestinationTableName = "dbo.tblPersons";

                //[OPTIONAL]: Map the Excel columns with that of the database table
                sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
                sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");
                con.Open();
                sqlBulkCopy.WriteToServer(dtExcelData);
                con.Close();
            
        
    

也可以关注link 以获得更多解释

【讨论】:

你的回答非常有帮助。我已经更新了我的问题,现在我对布尔数据只有一点点问题。在这里,当我检查布尔字段检查错误时。 是的,我可以,但目前我有点忙,我工作完成后会尽快回复您。希望你没事。 您的问题类似于“new DataColumn("User_id",typeof(string))”,它是在索引位置 22 处创建的,当您尝试在位置索引 23 处映射列时在 "sqlBulkCopy.ColumnMappings.Add("User_id",dtExcelData.Columns[int.Parse(txt_col22.Text.Trim())].ToString());"所以它无法在位置索引 23 处找到“User_id”列,导致发生错误。 我无法从这里猜出这个舞会,或者修复它,如果我能处理你的项目,我可能会尝试。但是需要你的项目。 确保源和目标中的字段顺序相同。

以上是关于如何导入 xls 并将行分配给表列?的主要内容,如果未能解决你的问题,请参考以下文章

如何将上传的 CSV 或 XLS 文件中的数据自动导入 Google 表格

添加行时如何获取表列的值

如何使用 pyspark 将 null 分配给配置单元表列

如何将函数与表连接起来,并将表列作为参数传递给雪花中的函数

如何将xls文件导入MySQL表

XCode:使用命令行工具,如何从文件夹创建 git 并将其导入项目