如何使用 DocumentFormat.OpenXML 或 ClosedXML C# 从 Excel 获取合并单元格

How to get a merged cell from Excel using DocumentFormat.OpenXML or ClosedXML C#

我只需要使用 DocumentFormat.OpenXml 或 ClosedXML 获取合并单元格的区域,该区域以 Excel 结尾的行号,如何为每个单元格执行此操作?

我发现这有点笨拙,但我相信这是正确的方法。

private static void GetMergedCells()
{
    var fileName = $"c:\temp\Data.xlsm";

    // Open the document.
    using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
    {
        // Get the WorkbookPart object.
        var workbookPart = document.WorkbookPart;

        // Get the first worksheet in the document.  You can change this as need be.
        var worksheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();

        // Retrieve the WorksheetPart using the Part ID from the previous "Sheet" object.
        var worksheetPart = (WorksheetPart)workbookPart.GetPartById(worksheet.Id);

        // Retrieve the MergeCells element, this will contain all MergeCell elements.
        var mergeCellsList = worksheetPart.Worksheet.Elements<MergeCells>();

        // Now loop through and spit out each range reference for the merged cells.
        // You'll need to process the range either as a string or turn it into another
        // object that gives you the end row.
        foreach (var mergeCells in mergeCellsList)
        {
            foreach (MergeCell mergeCell in mergeCells)
            {
                Console.WriteLine(mergeCell.Reference);
            }
        }
    }
}

如果您还不知道,这是在使用 DocumentFormat.OpenXml.Spreadsheet

使用 ClosedXML,可以通过以下方式完成:

var ws = workbook.Worksheet("Sheet 1");
var cell = ws.Cell("A2");
var mergedRange = cell.MergedRange();
var lastCell = mergedRange.LastCell();

// or 
var lastCellAddress = mergedRange.RangeAddress.LastAddress;