【问题标题】:Can I get the Excel row number using OleDB?我可以使用 OleDB 获取 Excel 行号吗?
【发布时间】:2019-09-04 05:58:26
【问题描述】:

我正在用 C#(和 SQL Server)处理 Excel 数据。我需要能够向最终用户报告任何有问题的 Excel 行。这样做的自然方法是给 Excel 行号。但是,目前尚不清楚如何获取该行号以供参考。

我有这样的事情:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyWorkSheet$", conn);

并且想要这样的东西:

OleDbCommand cmd = new OleDbCommand("SELECT ExcelRowId,* FROM MyWorkSheet$," conn);

SQL's: ROW_NUMBER() 确实有效,因为我无法提供适当的 ORDER BY。 Excel 的:查询字符串中无法访问 ROW()。

【问题讨论】:

    标签: c# excel oledb


    【解决方案1】:

    到目前为止,答案似乎是“否”,但我可以稍后再创建它。

    int row;
    foreach (DataTable t in ds.Tables)
    {
        t.Columns.Add("RowNum",typeof(Int32));
        row = 1;
        foreach (DataRow r in t.Rows)
        {
            r["RowNum"] = row++;
        }
    }
    

    这似乎是可靠的,但它仍然感觉像是可以更自然地发生的事情。

    【讨论】:

      【解决方案2】:

      以以下示例代码为基础 (Karl Kieninger):

      int row;
      foreach (DataTable t in ds.Tables)
      {
          t.Columns.Add("RowNum",typeof(Int32));
          row = 1;
          foreach (DataRow r in t.Rows)
          {
              r["RowNum"] = row++;
          }
      }
      

      Excel行号可以这样获取:

      每个数据表对象(

      DataTable t;
      

      ) 有一个DataTable.Rows Property (

      t.Rows
      

      ) 返回一个DataRowCollection Class。使用DataRowCollection.IndexOf(DataRow) Method (

      t.Rows.IndexOf(r)
      

      ),您可以知道与Excel文件中的行号相关的Datatable中行的索引。所以,用 r.IndexOf(r) 替换 row++ 就可以了:

      int row;
      foreach (DataTable t in ds.Tables)
      {
          t.Columns.Add("RowNum",typeof(Int32));
          row = 1;
          foreach (DataRow r in t.Rows)
          {
              r["RowNum"] = r.IndexOf(r);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多