尝试从*.XLS 文件读取数据。我能够读取所有单元格字符串,但无法读取单元格中的数字。我尝试使用 .ToString() 方法但没有成功。取回数据库null。
代码:
public xlsConverter(string excelFilePath, int numColumns)
{
string cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=No;'", excelFilePath);
string queryStr = "SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(cnnStr))
{
OleDbCommand command = new OleDbCommand(queryStr, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for(int i = 0; i <= numColumns; i++)
{
cleanedString.AppendFormat("{0}{1}", (reader[i].ToString()), "|");
}
cleanedString.AppendLine();
}
reader.Close();
}
}
cleanedString.AppendFormat("Row[{0}], DataType[{1}], String[{2}], Column[{3}] |-|", counter, (reader[i]).GetType(), reader[i].ToString(), i);
产品:
Row[98], DataType[System.DBNull], String[], Column[4] |-|
第 4 列包含混合字符串和数字,例如:1300、2341、5000、4000 (DED)、1243
尝试使用“GetInt、GetValue、Parse、‘casting’、ToString() 等”,但 null 就是 null!有人想引导我走向正确的方向吗?
示例 XLS 文件:
https://github.com/abflett/adamflett_ca
https://github.com/abflett/adamflett_ca/blob/master/sample.xls
最佳答案
进行了一些挖掘,但最终得到了一个简单的修复。
连接字符串是问题所在。
string cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'", excelFilePath);
ImportMixedTypes=Text;TypeGuessRows=0
^已添加!
我在 YouTube 视频中找到了它: https://www.youtube.com/watch?v=jhPp_Hz54BU
并且已经在 stackoverflow 上回答了: Help with a OleDB connection string for excel files
关于c# - OleDbDataReader 如何读取数字类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36723035/