我正在尝试阅读excel文件。一些单元格包含公式,并被读作“#REF!”。我只想要数字运算的单元格值,我不关心公式。有办法处理公式吗?我可以在OLEDB中执行此操作还是应该切换到互操作?提前致谢。
var connectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=NO;IMEX=1""", fileName);
string firstSheetName;
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
DataTable dt = con.GetSchema("Tables");
firstSheetName = dt.Rows[0]["TABLE_NAME"].ToString();
}
var adapter = new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
var data = ds.Tables["anyNameHere"];
string cellValue = (string)data.Rows[i].ItemArray[4];
我尝试将“TypeGuessRows = 0; ImportMixedTypes = Text”添加到connectionstring。
var connectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=NO;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text""", fileName);
并没有帮助。
答案 0 :(得分:1)
试试这个。而不是使用Get模式,请使用getoledbschema。
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName=GettingSheetName(dtExcelSchema);
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();