更新:微软似乎真的不建议在服务器上使用 Excel COM 服务。尽管如此,许多开发人员在非 .NET(就像我的雇主所做的那样)和 .NET(请参阅此处)环境中都这样做,因为替代方案的成本很高。所有问题大部分都是可以解决的(除了大容量应用程序中潜在的可扩展性和性能问题以及在某些情况下的许可问题)。昂贵的替代方案是使用这样的第三方解决方案。
当一列中有不同数据类型的数据时,不应使用 OleDbConnection。您可以尝试使用 Excel COM/OLE API 从 Excel 读取,例如(从此处编译,可能包含错误):
在项目中包含以下参考:
Microsoft Excel 10.0 对象库
Microsoft Office 10.0 对象库
包括名称空间 Excel。
using Excel;
...
Excel.ApplicationClass xl = new Excel.Application();
xl.Visible = false;
xl.UserControl = false;
Excel.Workbook theWorkbook = xl.Workbooks.Open(
fileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
System.Array myvalues;
Excel.Range range = worksheet.get_Range("A1", "E1".ToString());
myvalues = (System.Array)range.Cells.Value;
重要的!您应该释放使用的资源。从这里:
// Need all following code to clean up and extingush all references!!!
theWorkbook.Close(null,null,null);
xl.Workbooks.Close();
xl.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (range);
System.Runtime.InteropServices.Marshal.ReleaseComObject (sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject (xl);
System.Runtime.InteropServices.Marshal.ReleaseComObject (worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (theWorkbook);
worksheet=null;
sheets=null;
theWorkbook=null;
xl = null;
GC.Collect(); // force final cleanup!