How to create an Excel file using the API of the Apache POI library
You can create Excel files using the API of the Apache POI library. Firstly, you need to add Apache POI dependencies to the pom.xml file of the project:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Next, you can use the following example code to create an Excel file with two columns of data:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelCreator {
public static void main(String[] args) throws IOException {
//Create Workbook
Workbook workbook = new XSSFWorkbook();
//Create a worksheet
Sheet sheet = workbook.createSheet("Sheet1");
//Create header
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("Name");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("Age");
//Create Data Rows
Row dataRow = sheet.createRow(1);
Cell dataCell1 = dataRow.createCell(0);
dataCell1.setCellValue("Alice");
Cell dataCell2 = dataRow.createCell(1);
dataCell2.setCellValue(25);
//Create file output stream
FileOutputStream fileOutputStream = new FileOutputStream("example.xlsx");
//Write Workbook to Output Stream
workbook.write(fileOutputStream);
//Close output stream
fileOutputStream.close();
//Close Workbook
workbook.close();
}
}
This sample code will create an Excel file with two columns of data, the first column being Name and the second column being Age, with the data line Alice (25 years old). Finally, the file will be saved as a file named example.xlsx.