我遇到了这样的问题。我试图读取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)
{
}
一切正常,我得到一个数据表,数据作为字符串数据类型,并在程序级别解析它们(我只在一列中混合数据类型)。但是当单元格具有数字格式并且该单元格的值(例如,0589)时,我需要在单元格中添加前导撇号,因为0必须存在于4位数字中。当我尝试使用IMEX参数1读取这样的excel文件时,我从该单元格获得了NULL值。我不明白为什么,我把所有数据都读成字符串数据类型。
答案 0 :(得分:0)
将单元格的数字格式更改为&#34; 0000&#34;对于一个始终为4位数的数字并保留前导零。
答案 1 :(得分:0)
正如我解决的那样,在加载电子表格之前,我在程序级别将注册表项TypeGuessRows设置为零,并在加载回8之后(如果其他程序将使用它)。
答案 2 :(得分:0)
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();