我无法读取Excel单元格中有前导撇号的单元格
本文关键字:单元格 读取 Excel | 更新日期: 2023-09-27 18:23:57
我遇到了这样一个问题。我试图读取Excel文件的数据,所有数据都是字符串。我用了下面的代码。
try
{
var connectionString = string.Format( "Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties='"Excel 8.0;HDR=YES;IMEX=1'"", session["FilePath"] );
using (var adapter = new System.Data.OleDb.OleDbDataAdapter( "SELECT * FROM [Sheet1$]", connectionString ))
{
var ds = new DataSet();
adapter.Fill( ds, "workBook" );
workBook = ds.Tables["workBook"];
}
if (workBook == null)
throw new Exception( "Could not load imported spreadsheet!" );
if (workBook.Rows.Count <= 0)
throw new Exception( "You are use an empty spreadsheet!" );
foreach (DataColumn column in workBook.Columns)
column.ColumnName = column.ColumnName.Trim();
}
catch (Exception exc)
{
}
一切都很好,我得到了一个数据表,其中的数据是字符串数据类型,并在程序级对它们进行了解析(我只是在一列中有一个混合的数据类型)。但是,当单元格的格式为Number,并且该单元格的值为0589时,我需要在单元格中添加一个前导撇号,因为0必须出现在4位数字中。当我尝试使用IMEX参数1读取这样的excel文件时,我从这个单元格中得到了NULL值。我不明白为什么,我把所有数据都读成字符串数据类型。
将单元格的数字格式更改为"0000",表示始终为4位并保留前导零的数字。
正如我修复的那样,在加载电子表格之前,我在程序级别上将注册表项TypeGuessRows设置为零,在加载回8之后(以防其他程序使用它)。
string file = "C:''temp''Exposure''UTC.xlsx";
OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = file;
connStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX=1");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;
connection.Open();
// var myTableName = connection.GetSchema("Tables").Rows[0]["TABLE_NAME"];
DbCommand selectCommand = factory.CreateCommand();
string sql = "SELECT * FROM [Daily Monitoring$]";
selectCommand.CommandText = sql;
selectCommand.Connection = connection;
DbDataAdapter adapter = factory.CreateDataAdapter();
adapter.SelectCommand = selectCommand;
DataSet data = new DataSet();
adapter.Fill(data);
DataTable dt = data.Tables[0];
connection.Close();
string ss = dt.Rows[1][1].ToString();