简体   繁体   中英

Get row from Excel file in C#

I am reading through an Excel file in C#. There are 3 sheets in the file:

  1. Summary
  2. Users
  3. Others

I am looping through the columns of Summary sheet.(code below)

There is a column: SummaryID in every sheet.

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
   }
  }

My question is: for everyrow in Summary Sheet (SummaryID), I want to get all matching rows that match the SummaryID in 'Users' and 'Others' sheets .

Note: The column SummaryID exists in all 3 sheets and is the first column in all sheets.

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

Have you considered treating your Excel sheet like a Database and querying out the data you want using OLEDB or a similar technology?

This would be a simple Join query at that point - Might be faster...

You can use OleDB to do this. Code is similiar

 // 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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM