export Excel to DataTable using NPOI

后端 未结 11 1302
别那么骄傲
别那么骄傲 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:06

    You can use nuget package for NOPI

    ReadExcel

    Basic usage: ExcelImportHelper.ReadExcel(bytes);

    0 讨论(0)
  • 2021-02-19 04:07

    On Codeplex website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet.

    This is simplest example of it -

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    
    //.....
    
    private void button1_Click(object sender, EventArgs e)
    {
        HSSFWorkbook hssfwb;
        using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
        {
            hssfwb= new HSSFWorkbook(file);
        }
    
        ISheet sheet = hssfwb.GetSheet("Arkusz1");
        for (int row = 0; row <= sheet.LastRowNum; row++)
        {
            if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
            {
                MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
            }
        }
    }  
    
    0 讨论(0)
  • 2021-02-19 04:09

    You can try this easy way through NPOI:

    private DataTable GetDataTableFromExcel(String Path)
        {
            XSSFWorkbook wb;
            XSSFSheet sh;
            String Sheet_name;
    
            using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
            {
                wb = new XSSFWorkbook(fs);
    
                   Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
            }
            DataTable DT = new DataTable();
            DT.Rows.Clear();
            DT.Columns.Clear();
    
            // get sheet
            sh = (XSSFSheet)wb.GetSheet(Sheet_name);
    
            int i = 0;
            while (sh.GetRow(i) != null)
            {
                // add neccessary columns
                if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
                {
                    for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                    {
                        DT.Columns.Add("", typeof(string));
                    }
                }
    
                // add row
                DT.Rows.Add();
    
                // write row value
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                {
                    var cell = sh.GetRow(i).GetCell(j);
    
                    if (cell != null)
                    {
                        // TODO: you can add more cell types capatibility, e. g. formula
                        switch (cell.CellType)
                        {
                            case NPOI.SS.UserModel.CellType.Numeric:
                                DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                                //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;
    
                                break;
                            case NPOI.SS.UserModel.CellType.String:
                                DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;
    
                                break;
                        }
                    }
                }
    
                i++;
            }
    
            return DT;
        }
    
    0 讨论(0)
  • 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<DataColumn>()
            .Select(c => sheetRow.GetCell(c.Ordinal, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString())
            .ToArray();
        dataTable.Rows.Add(dtRow);
    }
    
    0 讨论(0)
  • 2021-02-19 04:16

    You can accomplish you task by doing this.

    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using NPOI.Util.Collections;
    using NPOI;
    using System.Collections.Generic;
    using NPOI.OpenXmlFormats.Spreadsheet;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.Util;
    
    public DataTable xlsxToDT(Stream str)
    {
    XSSFWorkbook hssfworkbook = new XSSFWorkbook(str);
    ISheet sheet = hssfworkbook.GetSheetAt(0);
    str.Close();
    
    DataTable dt = new DataTable();
    IRow headerRow = sheet.GetRow(0);
    IEnumerator rows = sheet.GetRowEnumerator();
    
    int colCount = headerRow.LastCellNum;
    int rowCount = sheet.LastRowNum;
    
    for (int c = 0; c < colCount; c++)
        dt.Columns.Add(headerRow.GetCell(c).ToString());
    
    while (rows.MoveNext())
    {
        IRow row = (XSSFRow)rows.Current;
        DataRow dr = dt.NewRow();
    
        for (int i = 0; i < colCount; i++)
        {
            ICell cell = row.GetCell(i);
    
            if (cell != null)
                dr[i] = cell.ToString();
        }
        dt.Rows.Add(dr);
    }
    return dt;
    

    }

    0 讨论(0)
提交回复
热议问题