【问题标题】:Convert html tag to ClosedXml RichText将 html 标签转换为 ClosedXml RichText
【发布时间】:2023-03-30 03:22:01
【问题描述】:

我正在使用 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 标签(灰色)。

【问题讨论】:

    标签: c# regex excel richtext closedxml


    【解决方案1】:

    我是这样解决的:

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

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 2023-04-04
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2017-01-15
      相关资源
      最近更新 更多