0

I cannot find a way to style a single excel cell in different styles. For example I need to make only some part of the string bold and leave the rest unbold in one cell. I can only access Cells not characters in OpenXml.

enter image description here

Usually what I do to style the cell is,

ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets.Add("SheetName");
ws.Cells[1, 1].Style.Font.Bold = true;

I can't find a way to access characters in a cell. I saw some other excel plugins do the same but Is there any way OpenXml can do this? Any suggestions will be great. Thanks

Automate This
  • 30,726
  • 11
  • 60
  • 82
Zaheen Haris
  • 31
  • 1
  • 6

2 Answers2

0

The answer here works well.

You have to add the cell content as separate ExcelRichText objects.

Example:

ExcelRichText rt1 = ws.Cells[1, 1].RichText.Add("AB");
rt1.Bold = true; // bold just the "AB"
ExcelRichText rt2 = ws.Cells[1, 1].RichText.Add("CD");

Output will be: "ABCD"

Note: You will need to reference the namespace OfficeOpenXml.Style

apohl
  • 1,913
  • 27
  • 30
0

This is how you can add partial styles in an excel sheet using OpenXML.

        //Partial Cell Styling
        uint currentRow = 2;
        Row newRow = new Row() { RowIndex = currentRow };
        //create a new inline string cell
        Cell cell = new Cell() { CellReference = "J" + currentRow.ToString() };
        cell.DataType = CellValues.InlineString;
        
        //create a run for the bold text
        Run run1 = new Run();
        run1.Append(new Text("By: "));

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

        //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
        newRow.Append(cell);

        sheetData.Append(newRow);
Sahil Vig
  • 60
  • 1
  • 8