Excel removes formula added with EPPlus
我有一个使用 EPPlus 库创建的电子表格,其中包含 Unit (
公式为:
1 | =SWITCH(C3; ISBLANK(D3);"";"Percentage"; IF(ISNUMBER(D3); D3; 0) * IF(ISNUMBER(E3); E3; 0) / 100; IF(ISNUMBER(D3); D3; 0) * IF(ISNUMBER(E3); E3; 0)) |
当我将它粘贴到电子表格中的单元格
1 2 3 4 5 6 | for (var r = startAt + 2; r < endAt; r++) { var amountFormula = $"=SWITCH(C{r}; ISBLANK(D{r}); ""; "Percentage"; IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0) / 100; IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0))"; ws.Cells[$"F{r}"].Formula = amountFormula; } |
我对使用公式的每组行进行循环,因为它不是在每一行中都使用,例如标题、组总数等
当我尝试在 Excel 中打开电子表格时,它说有问题内容将被删除,如果我说是,它会删除公式的任何痕迹,如果我说不是,它不会打开电子表格。当我尝试通过代码添加公式时,我觉得存在某种字符编码问题或类似问题。粘贴时公式如何工作,但通过代码添加时会失败?
我不得不用逗号替换分号。我认为这对你来说是一个地区的事情,但 EPPlus 不支持它们:
https://github.com/JanKallman/EPPlus/wiki/Formula-Calculation
还必须指定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | [TestMethod] public void IsNumber_Formula_Test() { //https://stackoverflow.com/questions/58482284/excel-removes-formula-added-with-epplus //Throw in some data var dataTable = new DataTable("tblData"); dataTable.Columns.AddRange(new[] { new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(int)) }); for (var i = 0; i < 10; i++) { var row = dataTable.NewRow(); row[0] = i; row[1] = i * 10; row[2] = i * 100; dataTable.Rows.Add(row); } var fi = new FileInfo(@"c:\\temp\\IsNumber_Formula_Test.xlsx"); if (fi.Exists) fi.Delete(); using (var package = new ExcelPackage(fi)) { var workbook = package.Workbook; var ws = workbook.Worksheets.Add("Sheet1"); var cells = ws.Cells; cells["C1"].LoadFromDataTable(dataTable, true); var startAt = 0; var endAt = dataTable.Rows.Count + 2; for (var r = startAt + 2; r < endAt; r++) { //Had to use commas and specify the function domain //var amountFormula = $"=SWITCH(C{r}; ISBLANK(D{r}); ""; "Percentage"; IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0) / 100; IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0))"; var amountFormula = $"=_xlfn.SWITCH(C{r}, ISBLANK(D{r}), "", "Percentage", IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0) / 100, IF(ISNUMBER(D{r}), D{r}, 0) * IF(ISNUMBER(E{r}), E{r}, 0))"; ws.Cells[$"F{r}"].Formula = amountFormula; } package.Save(); } } |
给出这个: