使用 SqlBulkCopy 非常直接的导入:
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
{
excelConnection.Open();
OleDbCommand cmd = new OleDbCommand("Select " + fileID.ToString() + " as [FileID], * from [Sheet1$] where [Text] IS NOT NULL", excelConnection);
OleDbDataReader dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
sqlBulk.DestinationTableName = "table_name";
sqlBulk.ColumnMappings.Add(0, "FileID");
sqlBulk.ColumnMappings.Add(4, "Author");
sqlBulk.ColumnMappings.Add(3, "Title");
sqlBulk.ColumnMappings.Add(1, "Body");
sqlBulk.ColumnMappings.Add(2, "PublishedDate");
sqlBulk.BulkCopyTimeout = 600;
sqlBulk.WriteToServer(dReader);
}
}
数据进去,没问题。除了映射到正文 (nvarchar(max)) 的第一列被截断为 255 个字符。我环顾四周,发现了一些涉及更改注册表设置的解决方法的参考。将值设置为 0 以强制完全扫描,而不仅仅是前 8 行,这是 Excel 的默认值,但即使在重新启动后也无济于事。寻找其他想法。谢谢你。