How to Generate Excel File in Java

This step-by-step tutorial explains how to generate Excel file in Java using simple code. It is very common to generate an Excel file programmatically and fill data either by hardcoding it or by reading from some other source and filling into the desired sheet. For this purpose each cell is accessed and data is filled. Once all the data is filled, the workbook can be saved into any format like XLSX in this example.

Steps to Generate Excel File in Java

  1. Using Maven, add Aspose.Cells library to the project
  2. Add a reference to Workbook, Worksheet, and Cells classes using Import in the program
  3. Instantiate a Workbook class object
  4. Get a reference to the desired worksheet in the workbook
  5. Get a reference to the Cells collection in the desired worksheet
  6. Set values in different cells using the Cells collection
  7. Save the resultant file as XLSX

Above steps describe the procedure to create Excel file using Java. Aspose.Cells library is to be added to run this code. You may import a few classes like Workbook, Worksheet, and Cells where the Cells class is a collection of cells in the respective worksheet that provides access to each individual cell in the sheet. Using this collection set values in the desired cells and finally save the workbook in an Excel file format like XLSX used in this tutorial.

Code to Create an Excel File in Java

This sample code can be used to create Excel file using Java in Windows, macOS, and Linux. In this sample code, a Workbook object is initialized that contains a collection of worksheets. By default single sheet is added when a Workbook object is created. Each Worksheet contains a collection of cells that is used to access individual cells using the address like “A1” etc. String values are set to the cell however you can set any value like integer, decimal, date, and all other types supported by MS Excel. If you want to convert Excel file to some other format say XPS using a language other than Java say C#, you may refer to the article convert Excel to XPS in C#.

Note that there is no need to install MS Excel or use interop to run the above sample code.

 English