针对包含公式的 EXCEL Spreedsheet 的 SQL 查询
本文关键字:Spreedsheet SQL 查询 EXCEL 包含公 | 更新日期: 2023-09-27 18:31:46
我正在用C#编写一个组件,该组件使用Microsoft.ACE.OLEDB.12.0从EXCEl电子表格返回数据。 电子表格包含带有公式的单元格以及对该工作簿中其他电子表格的引用。 这些单元格不会向数据表返回任何数据。 请参阅下面的示例。
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][列] 在应该有一个值时是空的。 电子表格中的单元格包含以下引用
=dd!B2
这里有
一些关于填写和返回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];
}
}