简体   繁体   English

如何使用OpenXml在单元格中创建一些粗体文本

[英]How To make some text bold in cell using OpenXml

i have try to make bold the specific text using 我试图使用大胆的特定文本

 Bold fbld = new Bold();

but it will make bold hall cell. 但它会使大胆的霍尔细胞。

在此输入图像描述

Here in above image there is some bold text into the cell. 在上面的图像中,单元格中有一些粗体文本。

How can I do this in OpenXml using C#? 如何使用C#在OpenXml中执行此操作?

You need to use separate Run elements for the differently styled pieces of text. 您需要为不同样式的文本使用单独的Run元素。 You can add the bold by creating a RunProperties element and adding a Bold element to that. 您可以通过创建RunProperties元素并向其添加Bold元素来添加Bold

The following code will work on an existing spreadsheet that has no rows (note I haven't added the code for merging as that just adds complication - if you need help with that then please see 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM