Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read entire worksheet data in excel into DataTable using ClosedXml

Tags:

.net

closedxml

Excel Worksheet contains 60K records. Needs to be read and store into DataTable. Currently reading row by row. Is there any other better way using ClosedXml.

DataTable dt = new DataTable();
var wb = new XLWorkbook(fileName, XLEventTracking.Disabled);
using (wb)
{
    var ws = wb.Worksheet(1);
    using (ws)
    {                    
        var headerRow = ws.Row(3);
        int lastColumn = 32;
        foreach (var col in headerRow.Cells(true))
        {
            dt.Columns.Add(col.Value.ToString());
        }
        foreach (var row in ws.Rows().Skip(3))
        {
            var dr = dt.NewRow();
            for (int index = 0; index < lastColumn; index++)
            {
                dr[index] = row.Cell(index + 1).Value;
            }
            dt.Rows.Add(dr);
        }
    }
}
like image 549
kjana83 Avatar asked Aug 05 '17 14:08

kjana83


People also ask

How read data from Excel in C# using ClosedXML?

C# read Excel file using ClosedXML. Excel; using var wbook = new XLWorkbook("simple. xlsx"); var ws1 = wbook. Worksheet(1); var data = ws1.

Can ClosedXML read XLS file?

ClosedXML is a . NET library for reading, manipulating and writing Excel 2007+ (. xlsx, . xlsm) files.

What is the difference between OpenXml and ClosedXML?

Macros – ClosedXml doesn't support macros as its base library OpenXml also doesn't support it. Embedding – We cannot embed any file into Excel using ClosedXml, no APIs built for that, so some features of OpenXml still need to be implemented. Charts – No functionality related to charting is present.

Does ClosedXML require Excel?

Does ClosedXML require Excel? ClosedXML allows you to create Excel files without the Excel application.


1 Answers

You could use:

using (var wb = new XLWorkbook(fileName, XLEventTracking.Disabled))
{
    var ws = wb.Worksheet(1);
    DataTable dataTable = ws.RangeUsed().AsTable().AsNativeDataTable();
    /* Process data table as you wish */
}
like image 155
Francois Botha Avatar answered Sep 28 '22 03:09

Francois Botha