Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

c# - 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.

enter image description here

Here in above image there is some bold text into the cell.

How can I do this in OpenXml using C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use separate Run elements for the differently styled pieces of text. You can add the bold by creating a RunProperties element and adding a Bold element to that.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...