使用 OpenXML 创建合并单元格 [英] Create Merge Cells using OpenXML

查看:45
本文介绍了使用 OpenXML 创建合并单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个 Excel:

它是 XML:

我想使用 OpenXML 创建具有多个合并单元格的 Excel.

我该怎么做?

谢谢

解决方案

您可以使用

Please consider this Excel:

and it's XML:

I want to create such this Excel that has multiple merged cells using OpenXML.

How I can do this?

thanks

解决方案

You can use the MergeCells and MergeCell classes to create the merged cells you require. The MergeCells class is the collection of merge cells (<mergeCells count="3"> in your XML) and the MergeCell class represents each individual set of merged cells (<mergeCell ref="xx:xx" /> in your XML). To populate data in the merged cells you need to add the value to the upper left most cell; any other values will be ignored.

The following code will create a new file with merged cells.

using (SpreadsheetDocument myDoc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
    WorkbookPart workbookpart = myDoc.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();

    SheetData sheetData = new SheetData();

    //add a row
    Row firstRow = new Row();
    firstRow.RowIndex = (UInt32)1;

    //create a cell in C1 (the upper left most cell of the merged cells)
    Cell dataCell = new Cell();
    dataCell.CellReference = "C1";
    CellValue cellValue = new CellValue();
    cellValue.Text = "99999";
    dataCell.Append(cellValue);

    firstRow.AppendChild(dataCell);

    sheetData.AppendChild(firstRow);
    // Add a WorkbookPart to the document.
    worksheetPart.Worksheet = new Worksheet(sheetData);

    //create a MergeCells class to hold each MergeCell
    MergeCells mergeCells = new MergeCells();

    //append a MergeCell to the mergeCells for each set of merged cells
    mergeCells.Append(new MergeCell() { Reference = new StringValue("C1:F1") });
    mergeCells.Append(new MergeCell() { Reference = new StringValue("A3:B3") });
    mergeCells.Append(new MergeCell() { Reference = new StringValue("G5:K5") });

    worksheetPart.Worksheet.InsertAfter(mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());

    //this is the part that was missing from your code
    Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
    sheets.AppendChild(new Sheet()
    {
        Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
        SheetId = 1,
        Name = "Sheet1"
    });
}

The code above produces:

这篇关于使用 OpenXML 创建合并单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆