1

使用 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 的默认值,但即使在重新启动后也无济于事。寻找其他想法。谢谢你。

4

1 回答 1

0

我使用 ODBC 而不是 OLEDB,它不再将值截断为 255 个符号:

OdbcConnection con = new OdbcConnection(@"Driver={Microsoft Excel Driver
(*.xls)};DBQ=c:\temp\testbook.xls");
OdbcCommand cmd = new OdbcCommand(@"SELECT * FROM [Workbook1$]");
cmd.Connection = con;
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

您可以使用 2007 格式驱动程序访问 XLSX 文件: .... Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}...</p>

于 2015-06-18T17:05:32.873 回答