繁体   English   中英

如何使用NPOI C#将Excel读取到Datatable

[英]How to read Excel to Datatable using NPOI C#

我正在尝试使用NPOI将Excel读取到DataTable 。每件事都很好,但唯一的问题是,如果我们在该行中有任何Column单元为空,则无法读取。在Excel中,我有4行(每行都有一些空值)对于细胞)。

Excel File Image: 在此处输入图像描述

读取Excel到数据表后: 在此处输入图像描述

我想要这样的数据表

        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);
            DT.Rows[i][j] = sh.GetRow(i).GetCell(j);

        }
        i++;
        }
        return DT;
        }

请告诉我。

您可能需要尝试一些方法。 其可行的代码以使用NPOI读取Excel。

// read the current row data
XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
// LastCellNum is the number of cells of current rows
int cellCount = headerRow.LastCellNum;
 // LastRowNum is the number of rows of current table
int rowCount = sheet.LastRowNum + 1; 
 bool isBlanKRow = false;
//Start reading data after first row(header row) of excel sheet.

for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
{
    XSSFRow row = (XSSFRow)sheet.GetRow(i);
    DataRow dataRow = dt.NewRow();
    isBlanKRow = true;
    try
    {
        for (int j = row.FirstCellNum; j < cellCount; j++)
        {
            if (null != row.GetCell(j) && !string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
            {
                dataRow[j] = row.GetCell(j).ToString();
                isBlanKRow = false;
            }
        }
    }
    catch (Exception Ex)
     { 

     }
     if (!isBlanKRow)
     {
         dt.Rows.Add(dataRow);
     }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM