export Excel to DataTable using NPOI

后端 未结 11 1272
别那么骄傲
别那么骄傲 2021-02-19 03:22

I want to read Excel Tables 2010 xlsx using NPOI and then export data to DataTables but don\'t know how to use it. Can anyone show me step by step how to export Excel to Datatab

11条回答
  •  北海茫月
    2021-02-19 04:11

    Here's about the minimum code you can use to convert an Excel file to a DataSet using NPOI:

    IWorkbook workbook;
    using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
    {
        workbook = new HSSFWorkbook(stream); // XSSFWorkbook for XLSX
    }
    
    var sheet = workbook.GetSheetAt(0); // zero-based index of your target sheet
    var dataTable = new DataTable(sheet.SheetName);
    
    // write the header row
    var headerRow = sheet.GetRow(0);
    foreach (var headerCell in headerRow)
    {
        dataTable.Columns.Add(headerCell.ToString());
    }
    
    // write the rest
    for(int i = 1; i< sheet.PhysicalNumberOfRows; i++)
    {
        var sheetRow = sheet.GetRow(i);
        var dtRow = dataTable.NewRow();
        dtRow.ItemArray = dataTable.Columns
            .Cast()
            .Select(c => sheetRow.GetCell(c.Ordinal, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString())
            .ToArray();
        dataTable.Rows.Add(dtRow);
    }
    

提交回复
热议问题