【发布时间】:2016-04-19 15:33:43
【问题描述】:
试图从 *.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}], 列[{3}] |-|", 计数器, (reader[i]).GetType(), reader[i].ToString(), i);
生产:
行[98]、数据类型[System.DBNull]、字符串[]、列[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
【问题讨论】:
-
如果您确定它是一个数字,只需转换为您想要的类型。例如(int)读者[i];
-
试过了,甚至改成:cleanedString.AppendFormat("Row[{0}], DataType[{1}], String[{2}], Column[{3}] |- |", 计数器, (reader[i]).GetType(), reader[i].ToString(), i); System.DBNull 在具有数字数据类型的单元格上返回。我想也许我正在使用命令、查询或连接字符串丢失数据?
-
您能提供一些 .xls 文件中的示例数据吗?
-
编辑并提供了sample.xls
标签: c# wpf database type-conversion xls