EPPLUS 在插入时复制字符串

EPPLUS is duplicating strings on insert

我正在尝试将文本插入到 RichText 中,当插入的字符串的索引位于某个元素的末尾时,下一个元素会重复!

这是一个例子:

worksheet.Cells[rownum + 100, column].RichText.Add("first ");
worksheet.Cells[rownum + 100, column].RichText.Add(" second");
worksheet.Cells[rownum + 100, column].RichText.Text = worksheet.Cells[rownum + 100, column].RichText.Text.Insert(6, "Inserted");

结果:"first Insertedsecondsecond"

这是正常现象吗?因为我希望得到:

"first Inserted second"

我创建这个是为了模拟您的问题。

static void Main(string[] args)
{
    using (OfficeOpenXml.ExcelPackage ep = new OfficeOpenXml.ExcelPackage())
    {
        var ws = ep.Workbook.Worksheets.Add("sheet 1");
        ws.Cells[1, 1].IsRichText = true;
        ws.Cells[1, 1].RichText.Add("first ");
        ws.Cells[1, 1].RichText.Add(" second");
        ws.Cells[1, 1].RichText.Text = ws.Cells[1, 1].RichText.Text.Insert(6, "Inserted");

        Console.WriteLine(ws.Cells[1, 1].Text); // shows your bug
    }
}

这给出了 ws.Cells[1, 1].RichText

上包含 2 个项目的数组

其中第一个给出了您想要的值。

这并不能解决问题...

ws.Cells[1, 1].RichText.Add("first ");
ws.Cells[1, 1].RichText.Add(" second");
ws.Cells[1, 1].RichText.Text = ws.Cells[1, 1].RichText.Text.Insert(6, "Inserted");
ws.Cells[1, 1].RichText.RemoveAt(ws.Cells[1, 1].RichText.Count - 1);
Console.WriteLine(ws.Cells[1, 1].Text); 

问题出在有第二个项目的 richtext 集合中。不应该在那里。

ws.Cells[1, 1].RichText.Remove(ws.Cells[1, 1].RichText.Last());

甚至抛出异常!

我能想出的唯一解决办法是先清除 RichTextCollection 数组。

string curText = ws.Cells[1, 1].RichText.Text;
ws.Cells[1, 1].RichText.Clear(); // remove previous nodes
ws.Cells[1, 1].RichText.Text = curText.Insert(6, "Inserted");

完整示例代码:

static void Main(string[] args)
{
    using (OfficeOpenXml.ExcelPackage ep = new OfficeOpenXml.ExcelPackage())
    {
        var ws = ep.Workbook.Worksheets.Add("sheet 1");
        ws.Cells[1, 1].IsRichText = true;
        ws.Cells[1, 1].RichText.Add("first ");
        ws.Cells[1, 1].RichText.Add(" second");
        ws.Cells[1, 1].RichText.Add(" third");
        string curText = ws.Cells[1, 1].RichText.Text;
        ws.Cells[1, 1].RichText.Clear();
        ws.Cells[1, 1].RichText.Text = curText.Insert(6, "Inserted");

        Console.WriteLine(ws.Cells[1, 1].Text);
    }
}