设置共享公式
假设您有一个填充有数据的工作表,格式如下所示的样本工作表。
带有一列或数据的输入文件
您希望在B2中添加一个函数,用于计算第一行数据的销售税。税率为9% 。计算销售税的公式是:"=A2*0.09" 。本文介绍了如何使用Aspose.Cells应用此公式。
Aspose.Cells允许您使用Cell.Formula 属性来指定公式,具体来说是 Cell.setFormula() 和 Cell.getFormula() 。
有两种选项可将公式添加到列中的其他单元格(B3、B4、B5等)。
可以采取为第一个单元格所做的操作,有效地为每个单元格设置公式,相应地更新单元引用(A3*0.09
、A4*0.09
、A5*0.09
等)。这需要更新每行的单元引用。它还需要Aspose.Cells逐个解析每个公式,对于大型电子表格和复杂公式来说可能耗时。尽管循环可以压缩额外的代码行,但这也会增加额外的代码行。
另一种方法是使用共享公式 。使用共享公式可以自动更新每行的单元引用,因此税金将被正确计算。Cell.setSharedFormula 方法比第一种方法更高效。
以下示例演示了如何使用它。下面的屏幕截图显示了输出文件。
输出文件:应用共享公式
This file contains 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);