公式定义为执行计算并以单元格形式返回结果值的方程式。 它包含几个函数,单元格引用,函数运算符。 根据用户需求,公式可以简单也可以复杂。 可以将函数定义为Excel中的内置操作,该操作在单元格中返回结果值。 函数仅包含单元格引用和值。
在本文中,我将向您展示如何使用Free Spire.XLS for Java在Excel单元格中应用公式和函数。
Add Spire.Xls.jar as dependency
Method 1: Download Free Spire.XLS for Java pack, unzip it and you’ll get Spire.Doc.jar file from the “lib” folder. Import the jar file in your project as a dependency.
方法2:如果要创建Maven项目,则可以通过将以下配置添加到pom.xml来轻松添加jar依赖项。
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.xls.free</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
Using the code
import com.spire.xls.*;
public class InsertFormulas {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Declare two variables: currentRow、currentFormula
int currentRow = 1;
String currentFormula = null;
//Set the column width
sheet.setColumnWidth(1, 32);
sheet.setColumnWidth(2, 16);
//Write test data into cells
sheet.getCellRange(currentRow,1).setValue("Test data:");
sheet.getCellRange(currentRow,2).setNumberValue(1);
sheet.getCellRange(currentRow,3).setNumberValue(2);
sheet.getCellRange(currentRow,4).setNumberValue(3);
sheet.getCellRange(currentRow,5).setNumberValue(4);
sheet.getCellRange(currentRow,6).setNumberValue(5);
//Write text in cells
currentRow += 2;
sheet.getCellRange(currentRow,1).setValue("Formulas or functions:") ; ;
sheet.getCellRange(currentRow,2).setValue("result:");
//Format cells
CellRange range = sheet</