将html标记转换为ClosedXml RichText

时间:2017-12-13 14:18:14

标签: c# regex excel richtext closedxml

我正在使用ClosedXml在Excel文件中导出一些数据。

我想将包含一些html标签的字符串导出为<font color='gray'><s>....</s></font>,并将其翻译为RichText颜色为灰色并标记为。

执行此操作的代码如下:

cell.RichText.Substring(index, length).SetFontColor(XLColor.Gray).SetStrikethrough();

或者我也可以使用:

cell.RichText.AddText("foo")

问题是我还需要删除html标签。

我的代码:

string pattern = @"<font color='gray'><s>(\d+)<\/s><\/font>";

foreach (IXLCell cell in ws.Columns("A").CellsUsed())
{
    MatchCollection matches = Regex.Matches(cell.GetValue<string>(), pattern);
    foreach (Match match in matches)
    {
        foreach (Capture capture in match.Captures)
        {
              cell.RichText.Substring(capture.Index, capture.Length).SetFontColor(XLColor.Gray).SetStrikethrough();
              // only content in hmtl tags
              // cell.RichText.Substring(capture.Index + "<font color='gray'><s>".Length, capture.Length - "</s></font>".Length - "<font color='gray'><s>".Length).SetFontColor(XLColor.Gray).SetStrikethrough();
        }
     }
}

它有效,但它保留了html标签(灰色标记)。

1 个答案:

答案 0 :(得分:0)

我用以下方式解决了:

foreach (IXLCell cell in ws.Columns("A").CellsUsed())
{
    List<Capture> captures = new List<Capture>();
    MatchCollection matches = Regex.Matches(cell.GetValue<string>(), pattern);
    foreach (Match match in matches)
    {
        foreach (Capture capture in match.Captures)
        {
            captures.Add(capture);
        }
    }

    cell.Value = cell.GetValue<string>().Replace("<font color='gray'><s>", "").Replace("</s></font>", "");
    int contatore = 0;
    foreach (Capture capture in captures)
    {
        cell.RichText.Substring(capture.Index - contatore, capture.Length - "</s></font>".Length - "<font color='gray'><s>".Length).SetFontColor(XLColor.Gray).SetStrikethrough();
        contatore += "<font color='gray'><s></s></font>".Length;
    }
}