This brief tutorial describes how to display formulas in Excel using Java. It has the details to establish the environment, a step-by-step process to write the application, and a runnable sample code to display all formulas in Excel using Java. It demonstrates a complete scenario where this feature is exercised for a newly created workbook that is saved in XLSX format however, you may use other formats also like XLS, ODS, etc.
Steps to Show Formulas in Excel using Java
- Establish the environment to add Aspose.Cells to display formulas
- Create a workbook and get access to the first worksheet for showing its formulas
- Add values and formulas in some cells and calculate the formulas
- Set the ShowFormulas flag for the selected worksheet
- Save the resultant workbook with formulas displayed in it
These steps explain the process to display cell formulas in Excel using Java. All the classes, methods, and properties are mentioned that are used to accomplish this task. The Worksheet class property ShowFormulas is the main property that is to be set to achieve the requirement.
Code to Display Cell Formulas using Java
import com.aspose.cells.License; | |
import com.aspose.cells.Workbook; | |
import com.aspose.cells.Worksheet; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to display formulas using Java | |
// Instantiate the license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Create a workbook | |
Workbook workbook = new Workbook(); | |
// Access the first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Set cell values, formulas and calculate formula | |
worksheet.getCells().get("A1").setValue(10); | |
worksheet.getCells().get("B1").setValue(20); | |
worksheet.getCells().get("C1").setFormula(" = A1 + B1"); | |
workbook.calculateFormula(); | |
// Show formulas | |
worksheet.setShowFormulas(true); | |
// Save the workbook | |
workbook.save("ExcelWithFormula.xlsx"); | |
System.out.println("Done"); | |
} | |
} |
In this article, we have learned the process to display formulas in Excel using Java however, if you want to remove formulas without deleting the data, refer to the article on how to remove formula but keep data in Java.