【问题标题】:How To make some text bold in cell using OpenXml如何使用 OpenXml 使单元格中的某些文本变为粗体
【发布时间】:2021-07-01 07:29:27
【问题描述】:

我已经尝试使用加粗的特定文本

 Bold fbld = new Bold();

但它会使大厅单元格变粗。

在上图中,单元格中有一些粗体文本。

如何在 OpenXml 中使用 C# 做到这一点?

【问题讨论】:

    标签: c# openxml-sdk


    【解决方案1】:

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

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

    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-bod 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多