我有这个代码可以正常工作并将excel数据加载到SQL表中。唯一的问题是它还为所有列插入一个带有NULL值的新行。
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();
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + Path.GetFileName(excelPath) + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.mySQLTable";
sqlBulkCopy.BulkCopyTimeout = 200;
sqlBulkCopy.ColumnMappings.Add("Employee", "Employee_Name");
sqlBulkCopy.ColumnMappings.Add("Sal/Hourly", "Sal/Hourly");
sqlBulkCopy.ColumnMappings.Add("Total", "Total");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
这个2988行在excel中不存在,但是代码会创建它。任何帮助表示赞赏。
答案 0 :(得分:1)
您可以将查询更改为跳过excel中的空行:
"SELECT * FROM [" + Path.GetFileName(excelPath) + "] WHERE [Employee] IS NOT NULL"
这应该避免将空行添加到DataTable
。当然你也可以在以后删除它们,但效率会降低。例如:
dtExcelData = dtExcelData.AsEnumerable()
.Where(r => !String.IsNullOrEmpty(r.Field<string>("Employee")))
.CopyToDataTable();