【问题标题】:Get row from Excel file in C#从 C# 中的 Excel 文件中获取行
【发布时间】:2023-03-28 16:24:02
【问题描述】:

我正在阅读 C# 中的 Excel 文件。文件中有 3 张工作表:

  1. 总结
  2. 用户
  3. 其他

我正在遍历摘要表的列。(下面的代码)

每张纸都有一列:SummaryID

foreach (DataColumn dc in Summary.Columns)
 {
   foreach (DataRow dr in Summary.AsEnumerable())
   {
     //get column SummaryID for everyrow
     //And then get all rows in Users sheet that match  SummaryID
     //And then get all rows in Others sheet that match SummaryID
   }
  }

我的问题是:对于摘要表 (SummaryID) 中的每一行,我想获取与“用户”和“其他”表中的 SummaryID 匹配的所有匹配行

注意:SummaryID 列存在于所有 3 张工作表中,并且是所有工作表中的第一列。

【问题讨论】:

  • 你的问题是什么..你做了一个陈述而不是一个问题..你应该问get matching row based on SummaryID这是一个正确的假设吗..?你能展示你是如何连接到 Excel 电子表格的吗?您是否有声明 Excel 应用程序实例的现有代码?

标签: c# excel


【解决方案1】:

我喜欢使用LinqToExcel 他们有一个 LinqToExcel.Row 类可能对您有所帮助,并且您将使用 linq 而不是 foreach 语句。

【讨论】:

    【解决方案2】:

    您是否考虑过将您的 Excel 工作表视为数据库,并使用OLEDB 或类似技术查询出您想要的数据?

    此时这将是一个简单的 Join 查询 - 可能会更快...

    【讨论】:

    • 我确信应该有一种方法可以简单地获取整行。我的问题是:对于摘要表(SummaryID)中的每一行,我想获取与“用户”和“其他”表中的 SummaryID 匹配的所有匹配行。注意:“SummaryID”列存在于所有 3 个工作表中,并且是所有工作表中的第一列。
    • ...我不确定您要了解什么,但我仍然相信最快的方法是将 Excel 文件视为数据库 - 如果您希望每个工作表中的数据分开,您只需从摘要表中选择不同的SummaryID,然后从SummaryID 在该列表中的其他两张表中选择*。大功告成!
    【解决方案3】:

    您可以使用 OleDB 来执行此操作。代码类似

     // create a connection to your excel file
        // the 8.0 denotes excel 2003
        // you will need to use the right number for your version of excel
        OleDbConnection con = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=InsertYourFile.xls"; Extended Properties=Excel 8.0" );
    
        // create a new blank datatableDataTable 
       dtSheets = new DataTable();
    
        // create a data adapter to select everything from the worksheet you want
        OleDbDataAdapter da = new OleDbDataAdapter( "select * from [YourWorksheetName$] WHERE BLAH, etc", con );
    
    
       // use the data adapter to fill the datatable
       da.Fill( dtSheets );
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多