EPPLUS在插入时复制字符串 [英] EPPLUS is duplicating strings on insert
问题描述
我正在尝试将文本插入RichText,当插入的字符串的索引位于元素的末尾时,下一个元素将重复!
I am trying to insert text into RichText, when the index of the inserted string is at the end of an element the next element gets duplicated!
这里是一个例如:
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
Result: "first Insertedsecondsecond"
这是正常行为吗?因为我期望得到:
Is this normal behavior? because I am expecting to get:
第一个插入第二个
推荐答案
我创建了这个程序来模拟您的问题。
I created this to simulate your issue.
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个项目,其中第一个给出您想要的值。
where the first one gives your desired value.
这不能解决问题...
this does not fix it...
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集合中有第二个项目。
The problem is in the richtextcollection having a second item. which should not be there.
ws.Cells[1, 1].RichText.Remove(ws.Cells[1, 1].RichText.Last());
甚至抛出异常!
我唯一能想到的解决方案是先清除RichTextCollection的数组。
The only solution I can come up with is to clear the array of RichTextCollection first.
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);
}
}
这篇关于EPPLUS在插入时复制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!