【发布时间】:2019-10-26 05:46:19
【问题描述】:
我使用以下代码读取了 xls 文件:
private static DataSet GetDataSetFromExcelFilePath(string filePath)
{
try
{
//Microsoft.Jet.OLEDB.4.0
using (OleDbConnection oleDbConnection = new
OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=\"Excel 8.0;Persist Security Info=False;HDR=No;IMEX=1;\"", filePath)))
//OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=\"Excel 8.0;Persist Security Info=False;HDR=No;IMEX=1\"", filePath)))
// using (OleDbConnection oleDbConnection = new
// OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=\"Excel 8.0;Persist Security Info=False;HDR=No;IMEX=1\"", filePath)))
{
oleDbConnection.Open();
DataTable schema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string sheetName = schema.Rows[0].Field<string>("TABLE_NAME");
var adapter = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", sheetName), oleDbConnection);
var dataSet = new DataSet();
adapter.Fill(dataSet, Path.GetFileName(filePath));
return dataSet;
}
}
catch (Exception ex)
{
return null;
}
}
请注意,我在连接字符串中设置了 IMEX 1,因此它会将所有数据读取为字符串,但我在客户端的一台机器上遇到了一个奇怪的问题,其中 AM/PM 或完整 HH 被完全忽略了一段时间。以下是使用上述代码填充数据集的方式:https://gyazo.com/f45c29c42b5d1339ae1fe159be4caf76 其中没有 AM 和 PM 的区别。
这是实际数据在 excel 中的显示方式:https://gyazo.com/caf91c165eb08e3110fd2c3b7d4b8c51
请注意,无法更改 Excel 格式或结构。最好在代码中进行任何可能的更改。
作为参考,如果有人想在这里下载 excel 文件进行测试,它是:https://www.dropbox.com/s/7824xh3ihlym9v9/test.xls?dl=0
当您将 Window 的语言设置为挪威时,还可以重现该问题,如下所示:https://gyazo.com/d03b3056ed81e177076471a74058fdb7
【问题讨论】:
标签: c# excel c#-4.0 .net-4.5 windows-server-2012