EPPLUS在插入时复制string
我想插入文本到RichText中,当插入的string的索引位于元素的末尾时,下一个元素被复制!
这里是一个例子:
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");
结果:“第一次插入第二秒”
这是正常的行为? 因为我期待得到:
“第一插入第二”
我创build了这个模拟你的问题。
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);
问题是richtextcollection有第二项。 这不应该在那里。
ws.Cells[1, 1].RichText.Remove(ws.Cells[1, 1].RichText.Last());
甚至会抛出一个exception!
我能想出的唯一解决scheme是首先清除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); } }