【问题标题】:How to read Excel to Datatable using NPOI C#如何使用 NPOI C# 将 Excel 读取到数据表
【发布时间】:2018-06-11 21:50:59
【问题描述】:

我正在尝试使用 NPOI 将 Excel 读取到 DataTable。一切正常,但唯一的问题是如果我们在该行中有任何列单元格为空,则为不阅读。在 Excel 中,我有 4 行(每行有一些单元格的空值)。

Excel 文件图片:enter image description here

读完那个 Excel 到数据表 :enter image description here

I want like this in data table

        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;
        }

请帮帮我。

【问题讨论】:

  • 它会抛出异常吗?它只是跳过这条线吗?
  • 它正在跳过单元格..不读取单元格值例如请附上图片
  • 例如在excel中我总共有4行..在第一行每个单元格都有值。在第二行只有第二个单元格的值,第三和第四个也相同..但最后它跳过并返回 4 行。
  • 请帮助我正在尝试,但我不明白这里发生了什么。
  • 你能帮帮我吗..这太紧急了请大家

标签: c# excel npoi


【解决方案1】:

您可能必须尝试沿着这条路线做一些事情。使用 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);
     }

}

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    相关资源
    最近更新 更多