This project has moved and is read-only. For the latest updates, please go here.

Reading and writing RichText values

May 26, 2014 at 8:12 PM
Edited May 27, 2014 at 9:21 AM
I need to read RichText value from a cell, modify it and write to another cell.

The following code nearly works (with version 4.0 Beta 2):
using (var p = new ExcelPackage(new FileInfo(OutputFileName)))
{
    var sheet = p.Workbook.Worksheets.First();

    var sourceCell = sheet.Cells[1, 1];
    var resultCell = sheet.Cells[2, 1];

    foreach (var rt in sourceCell.RichText)
    {
        var rtNew = resultCell.RichText.Add(rt.Text.Replace('a', 'b'));
        rtNew.Bold = rt.Bold;
        rtNew.Color = rt.Color;
        if (!String.IsNullOrEmpty(rt.FontName)) rtNew.FontName = rt.FontName;
        rtNew.Italic = rt.Italic;
        rtNew.PreserveSpace = rt.PreserveSpace;
        if (rt.Size > 0) rtNew.Size = rt.Size;
        rtNew.Strike = rt.Strike;
        rtNew.UnderLine = rt.UnderLine;
        rtNew.VerticalAlign = rt.VerticalAlign;
    }

    p.Save();
}
  1. When RichText consists of 2 parts, first ending with spaces, the spaces are lost in the result.
  2. When the first part of RichText has no custom styles applied, for the first element rt.FontName is an empty string and rt.Size is zero, so without my if statements the result is corrupted. Is that a bug or feature?
  3. Is there a more simple way to do this, without copying RichText elements with all properties one-by-one?
Feb 16, 2015 at 10:54 AM
The following code seems to work well with version 4.0.3.
using (var p = new ExcelPackage(new FileInfo(OutputFileName)))
{
    var sheet = p.Workbook.Worksheets.First();

    var sourceCell = sheet.Cells[1, 1];
    var resultCell = sheet.Cells[2, 1];

    sourceCell.Copy(resultCell);
    resultCell.IsRichText = true;

    foreach (var rt in resultCell.RichText)
    {
        rt.Text = rt.Text.Replace("text", "supertext");
    }

    p.Save();
}
But if I do not set IsRichText property for the result cell, I see xml markup in the sell instead of RichText value.
Why isn't this property set by the Copy function? Is that a bug or feature?