我在C#中编写一个组件,它使用Microsoft.ACE.OLEDB.12.0从EXCEl电子表格返回数据。电子表格包含具有公式的单元格以及对该工作簿中其他电子表格的引用。这些单元格不向DataTable返回任何数据。见下面的例子。
OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
OleDbCommand OleCommand = new OleDbCommand();
OleCommand.Connection = OleDBconn;
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(OleCommand);
OleCommand.CommandText = string.Format(@"SELECT [Column] From [Sheet1$]");
adp.SelectCommand = OleCommand;
adp.Fill(dt);
列包含具有公式的单元格以及对工作簿中其他工作表的引用。所以当它应该有一个值时,dt [0] [Column]为null。电子表格中的单元格包含以下参考
= DD!B2
答案 0 :(得分:0)
您可以尝试填写和返回DataTable
//call the method this way
var someDataTable = ExecuteDataSet("SELECT * FROM [Sheet1$]", InputFile);
public static DataTable ExecuteDataSet(string sql, string InputFile)
{
using (DataSet myDataset = new DataSet())
using (OleDbConnection OleDBconn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"",InputFile));
using (OleDbCommand cmdSelect = new OleDbCommand(sql, OleDBconn))
{
try
{
OleDBconn.Open();
dtXLS = OleDBconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//if you need to return this change the method signature to out param for this
new OleDbDataAdapter(cmdSelect).Fill(myDataset);
}
catch (Exception ex)
{
//Show a message or log a message on ex.Message
}
return myDataset.Tables[0];
}
}