Table of Contents

Rich text

A cell's text can be formatted in parts: a word bold, a number red, a subscript. XlsxDocumentCell.RichText reads those runs, SetRichText writes them, and a find and replace keeps them. Measured against Excel: it reports every character of what DocWright writes in the font DocWright gave it.

dotnet add package DocWright.Spreadsheet

Write

using DocWright.Core.Primitives;
using DocWright.Spreadsheet;

sheet.SetRichText("A1", new XlsxRichText(
    new XlsxRichTextRun("Total: "),                                  // the cell's own font
    new XlsxRichTextRun("1,234", new XlsxRunFormat { Bold = true, Color = ColorRgb.FromRgb(0xC0, 0, 0) }),
    new XlsxRichTextRun(" units", new XlsxRunFormat { Italic = true })));
sheet.SetRichText("A2", new XlsxRichText(
    new XlsxRichTextRun("H"),
    new XlsxRichTextRun("2", new XlsxRunFormat { ScriptPosition = XlsxScriptPosition.Subscript }),
    new XlsxRichTextRun("O is water")));

A run without a format takes the cell's own font, as Excel's first run does; a format states what it changes (FontName, Size, Color, Bold, Italic, Strike, Underline, ScriptPosition), and Excel takes the workbook's default font for anything left out. The cell keeps its own format: fill, borders, alignment.

Read

using DocWright.Spreadsheet;

XlsxDocumentCell total = notes.GetCell("A1");
Console.WriteLine($"A1 = '{total.Value.TextValue}'");
foreach (XlsxRichTextRun run in total.RichText!.Runs)
{
    Console.WriteLine($"  [{run.Text}] {(run.Format is null ? "the cell's font" : run.Format.ToString())}");
}

Value is the whole text, as for any text cell; RichText is null for plain text. Runs are read from shared and inline strings alike, colours resolved through the workbook's theme, and a run read from a file is written back as the file stated it.

Find and replace

using DocWright.Spreadsheet;

notes.ReplaceText("1,234", "2,468");     // takes the bold red of the run it starts in
notes.ReplaceText("water", "ice");
foreach (string reference in new[] { "A1", "A2" })
{
    Console.WriteLine(string.Join(" | ", notes.GetCell(reference).RichText!.Runs.Select(r => $"{r.Text} ({r.Format?.ToString() ?? "cell"})")));
}

ReplaceText, ReplaceRegex and ReplacePlaceholders keep the runs: the new text takes the format of the run where the match starts. Sheets copied within a workbook or into another keep them too.

Note

Edited cells are written as inline strings; the shared string table is never rewritten. Excel opens them as it opens any cell and turns them into shared strings on its own next save. A sheet converted to PDF draws a rich cell in the cell's own font, and says so.

Download the workbook: notes-rich.xlsx. The whole run prints:

A1 = 'Total: 1,234 units'
  [Total: ] the cell's font
  [1,234] bold #C00000
  [ units] italic
Total:  (cell) | 2,468 (bold #C00000) |  units (italic)
H (cell) | 2 (subscript) | O is ice (cell)