如何使用ClosedXml将excel中的整个工作表数据读入DataTable

时间:2017-08-05 14:24:00

标签: .net closedxml

Excel工作表包含60K记录。需要读取并存储到DataTable中。目前正在逐行阅读。还有其他更好的方法使用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);
                }
            }
        }

3 个答案:

答案 0 :(得分:1)

弗朗索瓦(Francois)的建议对我不起作用。我必须执行以下操作:

using (var wb = new XLWorkbook(fileName, XLEventTracking.Disabled))
{
    var dt = wb.Worksheet("worksheetName").Table(0).AsNativeDataTable();
    /* Process data table as you wish */
}

这是假设工作表中只有一个表。

答案 1 :(得分:1)

由于“ AsNativeDataTable();”引发了一些异常,因此上述答案对我不起作用。在读取某些包含无效数据或某些问题的单元格时。

我无法控制或管理/跳过抛出的异常,并且整个过程都停止了。

解决方案在这里

public static DataTable ExcelToDatatable_ClosedXML(System.IO.FileStream fileStream, string SheetName)
{
    //Offical way: DataTable dataTable = ws.RangeUsed().AsTable().AsNativeDataTable(); 
    //But cant manage and fix exceptions inside there

    try
    {
        DataTable dt = new DataTable();

        using (XLWorkbook workBook = new XLWorkbook(fileStream))
        {
            //Read the first Sheet from Excel file.
            IXLWorksheet workSheet = workBook.Worksheets.Where(x => x.Name.ToLower() == SheetName.ToLower()).FirstOrDefault();

            //Consider the first row as container column names
            bool firstRow = true;
            foreach (IXLRow row in workSheet.Rows())
            {
                //Use the first row to add columns to DataTable.
                if (firstRow)
                {
                    foreach (IXLCell cell in row.Cells())
                    {
                        dt.Columns.Add(cell.Value.ToString());
                    }
                    firstRow = false;
                }
                else
                {
                    //Add rows to DataTable.
                    dt.Rows.Add();
                    int i = 0;
                    foreach (IXLCell cell in row.Cells())
                    {
                        string val = string.Empty;

                        try
                        {
                            val = cell.Value.ToString();
                        }
                        catch { }

                        dt.Rows[dt.Rows.Count - 1][i] = val;
                        i++;
                    }
                }
            }
        }

        return dt;
    }
    catch
    {
        return null;
    }
}

用法

string filePath = HostingEnvironment.MapPath("~/Content/Storage/ProductsExcelImports/sample1.xlsx");
System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
var dt = ExcelToDatatable_ClosedXML(fileStream, "Sheet1");

谢谢

答案 2 :(得分:0)

您可以使用:

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