Append Rows of Datatable to Excel with Skip Some Columns on Excel on C#

I have one-to-one data in a datatable with my excel template. (The column names are the same.) I will print the data in this datatable exactly to the excel template, but I want to skip some columns, for example Column2. (I have 5000 lines of data, I do not want to break the Excel template.) Too long waiting for ClosedXml Save operation, I couldn't solve the reason. I would be very happy if you could help.

Example Table

My Code on Gist

Upvotes: 0

Views: 870

Answers (1)

Francois Botha
Francois Botha

Reputation: 4849

Build your own IEnumerable of an anonymous object and use the worksheet.FirstCell().InsertData() method to dump the entire enumerable into the worksheet.

I didn't test it, but the code would be something like this:

var data = dtData.Rows
    .Cast<DataRow>()
    .Select(r => new { Column1 = r["Column1"], Column2 = r["Column2"] })
    .ToList();

worksheet.FirstCell().InsertData(data);

Upvotes: 2

Related Questions