【问题标题】:SQL Query against EXCEL Spreedsheet containing formulas针对包含公式的 EXCEL 电子表格的 SQL 查询
【发布时间】:2016-01-28 01:07:00
【问题描述】:

我正在用 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] 应该有一个值时为空。电子表格中的单元格包含以下参考

=dd!B2

【问题讨论】:

  • 到目前为止有什么解决方案吗?我遇到了同样的问题...

标签: c# excel oledb


【解决方案1】:

关于填充和返回 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];
    }
}   

【讨论】:

  • 看起来像 cmdSelect.Open();应该是 OleDBconn.Open();。否则我试过了,我得到了相同的结果。
  • 您是否遇到任何错误,您能否提供更多相关信息
  • 当我为包含单元格引用或 Formula.dTable.Rows[1][5] {}跨度>
  • 如果您在QuickWatch myDataset.Tables[0] 中查看此值并点击小放大镜,是否表明数据表有数据行..?
  • 是的,我们确实有数据行。工作表中的确切行数。只是想知道 SQL 查询是否具有可用于强制单元格检索引用数据或执行公式的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多