在使用C#发送到SQL Server之前,将额外的列和值添加到excel文件中

我正在上传Excel文件并将数据插入到SQL Server中。 但问题是,在我发送Excel数据到SQL Server之前,我想在发送之前添加一个额外的列和值。

这是我试过的代码:

using (OleDbConnection exel_con = new OleDbConnection(conString)) { exel_con.Open(); string sheet1 = exel_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[12] { new DataColumn("Full Name", typeof(string)), new DataColumn("Email Address", typeof(string)), new DataColumn("ID Type",typeof(string)), new DataColumn("ID Number", typeof(string)), new DataColumn("Gender",typeof(string)), new DataColumn("Date of Birth", typeof(DateTime)), new DataColumn("Nationality",typeof(string)), new DataColumn("Married Status", typeof(string)), new DataColumn("Join Date", typeof(DateTime)), new DataColumn("Position",typeof(string)), new DataColumn("Salary/Wages Frequency", typeof(string)), new DataColumn("Salary/Wages Amount",typeof(int)) }); // Where I tried to add new column dtExcelData.Columns.Add("AdminId", typeof(int)); foreach (DataRow row in dtExcelData.Rows) { // Where I tried to add new value to the column. row["AdminId"] = 1; } using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", exel_con)) { oda.Fill(dtExcelData); } exel_con.Close(); string consString = ConfigurationManager.ConnectionStrings["PayrollSystem"].ConnectionString; using (SqlConnection con = new SqlConnection(consString)) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) { // Set the database table name sqlBulkCopy.DestinationTableName = "dbo.Employee"; //[OPTIONAL]: Map the Excel columns with that of the database table sqlBulkCopy.ColumnMappings.Add("AdminId", "AdminId"); sqlBulkCopy.ColumnMappings.Add("Full Name", "FullName"); sqlBulkCopy.ColumnMappings.Add("Email Address", "Email"); sqlBulkCopy.ColumnMappings.Add("ID Type", "IdType"); sqlBulkCopy.ColumnMappings.Add("ID Number", "IdNumber"); sqlBulkCopy.ColumnMappings.Add("Gender", "Gender"); sqlBulkCopy.ColumnMappings.Add("Date of Birth", "DateOfBirth"); sqlBulkCopy.ColumnMappings.Add("Nationality", "Nationality"); sqlBulkCopy.ColumnMappings.Add("Married Status", "MaritalStatus"); sqlBulkCopy.ColumnMappings.Add("Join Date", "JoinDate"); sqlBulkCopy.ColumnMappings.Add("Position", "Position"); sqlBulkCopy.ColumnMappings.Add("Salary/Wages Frequency", "SalaryFrequency"); sqlBulkCopy.ColumnMappings.Add("Salary/Wages Amount", "SalaryAmount"); con.Open(); sqlBulkCopy.WriteToServer(dtExcelData); con.Close(); } } } 

请任何帮助解决这个问题将不胜感激。

您应该将值添加到Fill() DataTable之后的新列。 直到你填充它,它没有任何行循环。

实际上,在填充DataTable之后,您应该添加新列,因为您将使用SELECT *来填充它,因此Excel中的列必须与DataTable中的列匹配。

所以,首先填写DataTable。 然后添加新的列和值。