设置共享公式
假设您有一个工作表,其中填充的数据格式类似于以下示例工作表。
包含一列或数据的输入文件
您想要在 B2 中添加一个函数来计算第一行数据的销售税。税收是9% .计算销售税的公式是:“=A2*0.09” .本文介绍如何将此公式应用于 Aspose.Cells。
Aspose.Cells 允许您使用Cell.Formula 财产,特别是Cell.setFormula() 和Cell.getFormula() .
有两个选项可用于将公式添加到列中的其他单元格(B3、B4、B5 等)。
要么做你对第一个单元格所做的,有效地为每个单元格设置公式,相应地更新单元格引用(A30.09,A4 0.09、A5*0.09 等)。这需要更新每一行的单元格引用。它还需要 Aspose.Cells 来单独解析每个公式,这对于大型电子表格和复杂的公式来说可能很耗时。它还添加了额外的代码行,尽管循环可以在一定程度上减少它们。
另一种方法是使用共享公式 .使用共享公式,公式会自动更新每行中的单元格引用,以便正确计算税金。这[Cell.setSharedFormula](https://reference.aspose.com/cells/java/com.aspose.cells/cell#setSharedFormula (java.lang.String,%20int,%20int)方法比第一种方法更有效。
下面的例子演示了如何使用它。下面的屏幕截图显示了输出文件。
输出文件:应用共享公式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SettingSharedFormula.class);
String filePath = dataDir + "input.xlsx";
// Instantiate a Workbook from existing file
Workbook workbook = new Workbook(filePath);
// Get the cells collection in the first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
// Apply the shared formula in the range i.e.., B2:B14
cells.get("B2").setSharedFormula("=A2*0.09", 13, 1);
// Save the excel file
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);