Search code examples
c#loopsforeachexceldatareader

How can I iterate over an excel file


How can I iterate over an excel file?

I currently have a class using ExcelDataReader

Class => https://paste.lamlam.io/nomehogupi.cs#14fXzlopygZ27adDcXEDtQHT0tWTxoYR

I have a excel file with 5 columns

This is my current code, but it is not exporting the result that I expect ...

TextWriter stream = new StreamWriter("excel Path");
//foreach string in List<string>
foreach(var item in ComboList) {
 var rows = ExcelHelper.CellValueCollection(item.Key);

 foreach(var row in rows) {
  stream.WriteLine(item.Key + "|" + row);
  break;
 }
}

stream.Close();

My result:

Column1|Row1
Column1|Row2
Column1|Row3
...
Column2|Row1
Column2|Row2
Column2|Row3
...

Expected:

Column1|Row1|Column2|Row1...
Column1|Row2|Column2|Row2...
Column1|Row3|Column2|Row3...

Thanks


Solution

  • If I understand what you want truly! I think you need to add a method like RowValueCollection to your ExcelHelper as below:

    public static IEnumerable<string[]> RowValueCollection()
    {
        var result = Data.Tables[0].Rows.OfType<DataRow>()
            .Select(dr => dr.ItemArray.Select(ia => ia.ToString()).ToArray());
        return result;
    }
    

    And then use it like this:

    var rowValues = ExcelHelper.RowValueCollection();
    foreach (var row in rowValues)
    {
        stream.WriteLine(string.Join("|", row));
    }
    

    HTH ;)