因此,客户将 Excel 文件上传给我们,我们有一个 Windows 服务,它会定期抓取新文件并将内容批量加载到我们的 SQL 服务器,如下所示:
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString))
{
excelConnection.Open();
OleDbCommand cmd;
cmd = new OleDbCommand("Select " + fileID.ToString() + " as [FileID],[AccountName],[Author],[Title],[Body] from [Sheet1$] where [Body] is not null;", excelConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["VI.OpenAmplify.Properties.Settings.DBConnection"].ConnectionString))
{
sqlBulk.DestinationTableName = "Web_OpenAmp_Posts";
sqlBulk.ColumnMappings.Add("FileID", "FileID");
sqlBulk.ColumnMappings.Add("AccountName", "AccountName");
sqlBulk.ColumnMappings.Add("Author", "Author");
sqlBulk.ColumnMappings.Add("Title", "Title");
sqlBulk.ColumnMappings.Add("Body", "Body");
sqlBulk.WriteToServer(dReader);
}
}
大多数时候都很好用,即使底部有一些空白行(WHERE 子句负责处理)。但有时我们会得到这些奇怪的文件,底部有很多(大约一百万)空白行,我们会得到一个带有 Unknown 的异常作为消息。如果我从 OleDbCommand 声明中删除 WHERE 子句,文件加载正常,但我们也会插入一百万行空白行。关于如何处理这个问题的任何想法?