简体   繁体   English

如何在Web窗体应用程序中使用asp.net c#将Excel数据上载到具有自动递增ID字段的SQL Server表中?

[英]How to upload Excel data into a SQL Server table with an auto incremented Id field using asp.net c# in a web forms application?

I read through a terrific post from Mudassar Ahmed Khan at http://www.aspsnippets.com/Articles/Import-Upload-CSV-file-data-to-SQL-Server-database-in-ASPNet-using-C-and-VBNet.aspx . 我阅读了Mudassar Ahmed Khan的精彩文章,网址为http://www.aspsnippets.com/Articles/Import-Upload-CSV-file-data-to-SQL-Server-database-in-ASPNet-using-C-and -VBNet.aspx It covers how to upload an Excel file into a SQL Server database table using asp.net and C#. 它涵盖了如何使用asp.net和C#将Excel文件上传到SQL Server数据库表中。

It works just fine, but I would like to get it to work for a table where the Id column is auto incremented. 它工作得很好,但是我想让它适用于Id列自动递增的表。 I would like to know how to modify the code to allow users to upload the file without having to specify a value for the Id column. 我想知道如何修改代码以允许用户上传文件而不必为Id列指定值。

Any help would be greatly appreciated. 任何帮助将不胜感激。

I'm using the code provided in the aforementioned tutorial as-is - I didn't make any changes. 我按原样使用上述教程中提供的代码-我没有做任何更改。 I'm just trying to understand how before I attempt to apply it to my actual application. 在尝试将其应用于实际应用程序之前,我只是想了解如何。

Please let me know if I need to provide additional information. 如果需要提供其他信息,请告诉我。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks, J 谢谢,J

Here is the code I would like to modify: 这是我要修改的代码:

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

Here is the aspx page markup: 这是aspx页面标记:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" OnClick = "Upload" runat="server" />

Here are the Excel specific connection strings for Excel 2003 and Excel 2007 or higher formats: 以下是Excel 2003和Excel 2007或更高版本格式的Excel特定连接字符串:

<add name = "Excel03ConString" connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name = "Excel07+ConString" connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

Since you can'nt use an identity column for bulkcopy you can add a column to the datatable: 由于无法将标识列用于批量复制,因此可以将列添加到数据表中:

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

dtExcelData.Columns.Add("Id", typeof(int));

int i = 0;
foreach(DataRow dr in dtExcelData.Rows)
{
    dr["Id"] = ++i;  
}
//...

暂无
暂无

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

相关问题 如何在C#ASP.Net中将表格数据从Excel上传到SQL Server 2008 - How to upload table data from Excel to SQL Server 2008 in C# ASP.Net 如何使用ASP.NET C#将Excel数据导入SQL Server,其中表的数据不在第一行开始? - How do you import Excel data to SQL Server using ASP.NET C# where the table's data does not start at the first row? 如何使用C#.net为Windows应用程序和使用C#ASP.NET的Web应用程序生成Excel文件 - how to generate excel file for a windows application using C# .net and a web application using C# ASP.NET 使用Asp.net C#中的文件上传功能将数据从.csv导入SQL Server - Import Data from .csv to SQL Server using File Upload in Asp.net C# 部署使用Asp.Net,C#和Sql Server 2008 R2构建的Web应用程序 - Deploying an Web Application built using Asp.Net,C# and Sql Server 2008 R2 Is there an API/ solution for Auto-saving data of lengthy web forms using MVC architecture (asp.net,c#,jquery,ajax) - Is there an API/ solution for Auto-saving data of lengthy web forms using MVC architecture (asp.net,c#,jquery,ajax) Excel文件使用asp.net C#读取数据并将其保存在SQL Server数据库中 - Excel file read and save data in SQL Server database using asp.net c# 来自Google文档的Excel使用asp.net C#读取数据并将其保存在SQL Server数据库中 - Excel from Google Docs read and save data in SQL Server database using asp.net c# ASP.NET Web Forms: How to reference CheckBoxList items as 'selected' on a table on another page using only C# and ASP.NET web forms? - ASP.NET Web Forms: How to reference CheckBoxList items as 'selected' on a table on another page using only C# and ASP.NET web forms? 使用ASP.NET C#Web表单验证多文件上传 - Validation for Multiple File upload using asp.net C# web forms
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM