复制 EPPlus 的相对公式不起作用



我在使用 EPPlus 将公式从一个单元格复制到另一个单元格时遇到问题。我希望副本根据单元格位置更改公式。我尝试使用复制函数,并尝试复制 FormulaR1C1 属性。无论哪种方式,公式都会损坏。

要重现错误,请将此公式复制到名为 c:\test\in.xlsx =VLOOKUP(B1,Sheet2!答:乙,2,假(

using System.IO;
using OfficeOpenXml;
namespace eptest
{
class Program
{
static void Main(string[] args)
{
ExcelPackage ep = null;
ExcelWorksheet ws = null;
ep = new ExcelPackage(new FileInfo("c:\test\in.xlsx"));
ws = ep.Workbook.Worksheets["Sheet1"];
ws.Cells[1, 1].Copy(ws.Cells[2, 1]);
//ws.Cells[2, 1].FormulaR1C1 = ws.Cells[1, 1].FormulaR1C1; //this doesn't work either
ep.SaveAs(new FileInfo("c:\test\out.xlsx"));
}
}
}

我想你发现了一个错误。 问题就在这里:

https://github.com/JanKallman/EPPlus/blob/d09fd3516b01c9fc6d6500ab9ff0ed82a60fab7b/EPPlus/ExcelCellBase.cs#L988

由于源单元格和目标之间有 1 行的增量,因此最终会调用UpdateFormulaReferences并尝试调整公式。 但是公式中A:B的部分是它无法正确识别和咀嚼它的整个范围。 我将在他们的 GitHub 页面上打开一个问题。

要绕过它,请执行以下操作:

//This does a literal string copy
ws.Cells[1, 1].Copy(ws.Cells[2, 1], ExcelRangeCopyOptionFlags.ExcludeFormulas);
ws.Cells[2, 1].Formula = ws.Cells[1, 1].Formula;

这样可以避免调用该函数,然后执行论坛的文字副本。 无法使用 R1C1,因为它也会尝试调整公式。

最新更新