如何使用OpenXML和C#从Excel文档中的合并单元格获取值

时间:2022-10-26 19:54:49

I have problem with merged cells. If I have value in first cell (B3) and this cell is merged with some others cells (for example C3, D3, E3, F3, F4) - in Excel document I can see only one value. This is great, but I would like to get from my GetCellValue function the same B3 value, when I ask for C3, D3, E3, F3 value.

我有合并细胞的问题。如果我在第一个单元格(B3)中有值并且此单元格与其他单元格合并(例如C3,D3,E3,F3,F4) - 在Excel文档中我只能看到一个值。这很棒,但我想从我的GetCellValue函数得到相同的B3值,当我要求C3,D3,E3,F3值时。

I suppose it is necessary to find all merged cells list and read value from the first one - but how to do this using OpenXml?

我想有必要找到所有合并的单元格列表并从第一个读取值 - 但是如何使用OpenXml执行此操作?

    public string GetCellValue(char ch, int y)
    {
        WorksheetPart wsPart = GetWorksheetPart(_sheetName);
        var addressName = new StringValue(ch + "" + y);

        Cell cell = wsPart.Worksheet.Descendants<Cell>().
            Where(c => c.CellReference.Value == addressName).FirstOrDefault();

        if (cell == null)
            return null;

        return cell.InnerText;
    }

UPDATE:

更新:

I have found partial solution (finding merged column names in OpenXML):

我找到了部分解决方案(在OpenXML中查找合并的列名称):

        List<MergeCells> mergeCells;
        WorksheetPart wsPart = GetWorksheetPart(_sheetName);
        if (wsPart.Worksheet.Elements<MergeCells>().Count() > 0)
        {
            mergeCells = wsPart.Worksheet.Elements<MergeCells>().ToList();
            string cells = mergeCells[0].OuterXml;
        }

1 个解决方案

#1


2  

if (wsPart.Worksheet.Elements<MergeCells>().Count() > 0)
{
     MergeCells mergeCells = wsPart.Worksheet.Elements<MergeCells>().First();
     foreach (MergeCell mergeCell in mergeCells)
     {
         // mergeCell.
     }
}

#1


2  

if (wsPart.Worksheet.Elements<MergeCells>().Count() > 0)
{
     MergeCells mergeCells = wsPart.Worksheet.Elements<MergeCells>().First();
     foreach (MergeCell mergeCell in mergeCells)
     {
         // mergeCell.
     }
}