[英]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.