2

My data is held in an IEnumerable object and I want that to be populated into a table in excel.

Basically I am able to export data to the Excel sheet but I dont know export a table in a more elegant way.

This is what I have:

 //Populate column names
 String[] columnNames = {"val1", "val2", "val3", "val4", "val5"};
 for (int p = 1, l = 1; l <= 5;l++)
 {
           xlWorkSheet.Cells[p, l] = columnNames[l-1]; 
 }

 //Entries is an IEnumerable object
 int i = 1;
 foreach (var e in Entries)
 {
            int j = 1;
            xlWorkSheet.Cells[i, j] = e.val1; j++;
            xlWorkSheet.Cells[i, j] = e.val2; j++;
            xlWorkSheet.Cells[i, j] = e.val3; j++;
            xlWorkSheet.Cells[i, j] = e.val4; j++;
            xlWorkSheet.Cells[i, j] = e.val5; j++; 
            i++; 
  }

I was thinking about converting the data from IEnumerable to datatable like this Convert IEnumerable to DataTable but i thought it will introduce an extra layer of unnecessary complexity.

What are your thoughts?

Thanks

Community
  • 1
  • 1
MTA
  • 739
  • 2
  • 9
  • 29

1 Answers1

2

I can highly recommend EPPlus for formatting Excel output. I had to do this recently and looked at many different approaches, but this was the best!

It really depends what you're trying to achieve though in terms of output.

From their documentation, EPPlus supports....

  • EPPlus supports:
  • Cell Ranges
  • Cell styling (Border, Color, Fill, Font, Number, Alignments)
  • Charts
  • Pictures
  • Shapes
  • Comments
  • Tables
  • Protection
  • Encryption
  • Pivot tables
  • Data validation
  • Conditional formatting
  • VBA
  • Many more...

EDIT: I just realised the question was about elegant ways to export. In which case, there's not much wrong with the way you're doing it already. But for formatting on the Excel end, I stand by my (largely irrelevant but useful to some) post. :)

Simon
  • 8,981
  • 2
  • 26
  • 32
  • Thanks. I'm looking into that now. – MTA Mar 21 '13 at 12:39
  • Thanks! this looks excellent, I might change my approach. I'm using Microsoft.Office.Interop.Excel but still didnt find out how to insert images with base64 format.. – MTA Mar 21 '13 at 12:48
  • No problem. The documentation is quite comprehensive if you search it using Google - and some examples can be found which make it easier. Hands down the best way I've found. – Simon Mar 21 '13 at 12:50