如何使用OpenXml在单元格中使一些文本加粗

13

我试图使用加粗来突出特定文本

 Bold fbld = new Bold();

但它将使单元格字体加粗。

在此输入图片描述

上图中,单元格内的一些文本加粗了。

我该如何使用C#中的OpenXml实现这个效果?

2个回答

30

您需要使用单独的Run元素来处理不同样式的文本。您可以通过创建一个RunProperties元素并将Bold元素添加到其中来添加粗体。

以下代码适用于没有行的现有电子表格(请注意,我没有添加合并代码,因为那只会增加复杂性 - 如果您需要帮助,请参见这里我的答案

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true))
{
    WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart;

    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

    //create a row
    Row row1 = new Row() { RowIndex = 1U };

    //create a new inline string cell
    Cell cell = new Cell() { CellReference = "A1" };
    cell.DataType = CellValues.InlineString;

    //create a run for the bold text
    Run run1 = new Run();
    run1.Append(new Text("ABC"));
    //create runproperties and append a "Bold" to them
    RunProperties run1Properties = new RunProperties();
    run1Properties.Append(new Bold());
    //set the first runs RunProperties to the RunProperties containing the bold
    run1.RunProperties = run1Properties;
            
    //create a second run for the non-bold text
    Run run2 = new Run();
    run2.Append(new Text(Environment.NewLine + "XYZ") { Space = SpaceProcessingModeValues.Preserve });

    //create a new inline string and append both runs
    InlineString inlineString = new InlineString();
    inlineString.Append(run1);
    inlineString.Append(run2);

    //append the inlineString to the cell.
    cell.Append(inlineString);

    //append the cell to the row
    row1.Append(cell);

    sheetData.Append(row1);
}

1
有点晚了,但希望对阅读的某人有用 :) 总的来说,记住 OpenXml 文件(xlsx、ppt、word)只是包含所有分离的 xml 文件的 zip 文件。 当我需要做一些事情时,我使用以下工作流程:
  • 创建一个带有一些示例数据的 Excel 文件并保存
  • 复制它,并应用你想要做的操作,例如将一个单元格加粗,并保存
  • 将两个文件重命名为 .zip 并将其解压到文件夹中
  • 比较文件夹之间的差异,我通常使用 WinMerge 进行比较
通过这样做,你可以看到当你将一个单元格加粗时发生了什么变化,并通过代码应用它。 这不是一个非常快速的方法,但它有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接