Creating an Excel File in Java Using Apache POI
Apache POI is a powerful Java library for working with Microsoft Office documents, including Excel. In this tutorial, we’ll demonstrate how to create an .xlsx
file, add a header row, and populate it with data using Apache POI.
Prerequisites
Before diving into the code, ensure that your project includes the Apache POI library. If you're using Maven, add the following dependencies to your pom.xml
:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
Java Program to Create and Write an Excel File
Here is a complete Java program that demonstrates how to create an Excel file, add a header row, and populate it with sample data:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWriter {
public static void main(String[] args) {
// Create a workbook
Workbook workbook = new XSSFWorkbook();
// Create a sheet
Sheet sheet = workbook.createSheet("Data");
// Create a header row
Row headerRow = sheet.createRow(0);
String[] headers = {"ID", "Name", "Age", "Department"};
// Add headers to the first row
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// Add sample data
Object[][] data = {
{1, "John Doe", 28, "Engineering"},
{2, "Jane Smith", 34, "Marketing"},
{3, "Samuel Green", 45, "HR"}
};
int rowNum = 1; // Start from the second row
for (Object[] rowData : data) {
Row row = sheet.createRow(rowNum++);
for (int colNum = 0; colNum < rowData.length; colNum++) {
Cell cell = row.createCell(colNum);
if (rowData[colNum] instanceof String) {
cell.setCellValue((String) rowData[colNum]);
} else if (rowData[colNum] instanceof Integer) {
cell.setCellValue((Integer) rowData[colNum]);
}
}
}
// Autosize the columns
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}
// Write to a file
try (FileOutputStream fos = new FileOutputStream("SampleData.xlsx")) {
workbook.write(fos);
System.out.println("Excel file written successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the workbook
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Explanation of the Code
-
Creating the Workbook and Sheet:
Workbook
: Represents the entire Excel workbook.Sheet
: Represents a sheet in the workbook where data will be written.
-
Adding a Header Row:
- A header row is created at index
0
with column names like "ID", "Name", "Age", and "Department".
- A header row is created at index
-
Populating Data:
- Sample data is defined as a 2D array and written row by row, starting from the second row (index
1
).
- Sample data is defined as a 2D array and written row by row, starting from the second row (index
-
Autosizing Columns:
- Columns are automatically resized to fit their content for better readability using
sheet.autoSizeColumn()
.
- Columns are automatically resized to fit their content for better readability using
-
Writing to a File:
- The workbook is saved to a file named
SampleData.xlsx
using aFileOutputStream
.
- The workbook is saved to a file named
-
Closing Resources:
- Resources are closed properly to prevent memory leaks.
Output
Running this program generates an Excel file SampleData.xlsx
with the following content:
ID | Name | Age | Department |
---|---|---|---|
1 | John Doe | 28 | Engineering |
2 | Jane Smith | 34 | Marketing |
3 | Samuel Green | 45 | HR |
If you want to insert data explicitly into specific cells, you can modify the code to directly reference each cell by its row and column indices. Here's the updated program
Java Program to Create and Write an Excel File with Explicit value insertion in cell
Key Changes
Explicit Data Insertion:
- Each cell is accessed and set individually using
Row.createCell(index).setCellValue(value)
. - For example,
row1.createCell(0).setCellValue(1)
explicitly sets the value1
in the first cell of the second row.
- Each cell is accessed and set individually using
Rows and Columns Defined:
- Each row is created explicitly, and cells within the row are defined for specific data points.
Output File:
- Saves the data into a file named
ExplicitSampleData.xlsx
Why Use Apache POI?
- Cross-Platform: Works seamlessly on all Java-supported platforms.
- Feature-Rich: Supports advanced features like formulas, formatting, and charts.
- Widely Used: Trusted by developers for handling Excel files programmatically.
Conclusion
This tutorial demonstrates how to create and write data to an Excel file using Java and Apache POI. By following this approach, you can easily generate Excel files for reporting, data export, or any other purpose.
Post a Comment