Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用NPOI从Excel电子表格检索合并单元格的值_C#_Excel_Npoi - Fatal编程技术网

C# 使用NPOI从Excel电子表格检索合并单元格的值

C# 使用NPOI从Excel电子表格检索合并单元格的值,c#,excel,npoi,C#,Excel,Npoi,我正在使用NPOI将数据从Excel检索到文本文件中。根据Excel表格,我应该以这种方式显示数据 Excel工作表中13/3/19的单元格跨两行合并,我不知道如何检索May的合并单元格值并显示它。有人有什么想法吗?在Excel中,如果一个单元格与其他单元格合并,则合并区域中的第一个单元格就是具有实际值的单元格。区域中的其他单元格为空白。合并的区域保留在工作表对象中,因为它们可以跨越多个行和列 要获取该值,您需要: 查看单元格本身的IsMergedCell属性,检查当前单元格是否合并 如果单元

我正在使用NPOI将数据从Excel检索到文本文件中。根据Excel表格,我应该以这种方式显示数据


Excel工作表中
13/3/19
的单元格跨两行合并,我不知道如何检索
May
的合并单元格值并显示它。有人有什么想法吗?

在Excel中,如果一个单元格与其他单元格合并,则合并区域中的第一个单元格就是具有实际值的单元格。区域中的其他单元格为空白。合并的区域保留在工作表对象中,因为它们可以跨越多个行和列

要获取该值,您需要:

  • 查看单元格本身的
    IsMergedCell
    属性,检查当前单元格是否合并
  • 如果单元格已合并,请在工作表上的合并区域中循环查找包含该单元格的区域
  • 找到包含区域后,从该区域获取第一个单元格
  • 从该单元格中获取值
  • 下面是我编写的一个助手方法,它应该可以完成以下任务:

    public static ICell GetFirstCellInMergedRegionContainingCell(ICell cell)
    {
        if (cell != null && cell.IsMergedCell)
        {
            ISheet sheet = cell.Sheet;
            for (int i = 0; i < sheet.NumMergedRegions; i++)
            {
                CellRangeAddress region = sheet.GetMergedRegion(i);
                if (region.ContainsRow(cell.RowIndex) && 
                    region.ContainsColumn(cell.ColumnIndex))
                {
                    IRow row = sheet.GetRow(region.FirstRow);
                    ICell firstCell = row?.GetCell(region.FirstColumn);
                    return firstCell;
                }
            }
            return null;
        }
        return cell;
    }
    
    cell = GetFirstCellInMergedRegionContainingCell(cell);
    if (cell != null)
    {
        // get the value
    }