Remove Excel Formulas but Keep Values in Java
The formulas in Excel can help caculate data quickly. After calculation, if you want to prevent some important formulas from being modified or viewed by others, you can remove the formulas but keep the values. In this article, you will learn how to implement this function in Java applications using Free Spire.XLS for Java.
Import JAR Dependency (2 Method)
1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<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>5.1.0</version>
</dependency>
</dependencies>
Sample Code
import com.spire.xls.*;
public class RemoveFormulas {
public static void main(String[] args) throws Exception {
//Create a workbook.
Workbook workbook = new Workbook();
//Load the file from disk.
workbook.loadFromFile("test.xlsx");
//Loop through worksheets.
for (Worksheet sheet : (Iterable<Worksheet>) workbook.getWorksheets())
{
//Loop through cells.
for (CellRange cell : (Iterable<CellRange>) sheet.getRange())
{
//If the cell contains formula, get the formula value, clear cell content, and then fill the formula value into the cell.
if (cell.hasFormula())
{
Object value = cell.getFormulaValue();
cell.clear(ExcelClearOptions.ClearContent);
cell.setValue(value.toString());
}
}
}
//Save to file
workbook.saveToFile("removeFormulasButKeepValues.xlsx", ExcelVersion.Version2013);
}
}