To read and write Excel files in Java using the Apache POI library, you can follow these steps:
Add Apache POI dependencies: First, you need to include the Apache POI dependencies in your Java project. You can download the JAR files from the Apache POI website (poi.apache.org) or use a build tool like Maven or Gradle to manage the dependencies.
Create a new Java class and import the necessary classes:
java
Copy code
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
Reading an Excel file:
To read data from an existing Excel file, you can use the following code:
try {
FileInputStream file = new FileInputStream("path/to/excel/file.xlsx");
// Create Workbook instance for the Excel file
Workbook workbook = new XSSFWorkbook(file);
// Get the first sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
// Iterate over rows in the sheet
for (Row row : sheet) {
// Iterate over cells in the row
for (Cell cell : row) {
// Get the cell value and print it
String cellValue = cell.getStringCellValue();
System.out.println(cellValue);
}
}
// Close the file
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing to an Excel file:
To create a new Excel file or modify an existing one, you can use the following code:
try {
// Create a new Workbook
Workbook workbook = new XSSFWorkbook();
// Create a new sheet
Sheet sheet = workbook.createSheet("Sheet1");
// Create a new row and set values
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello");
// Write the workbook to a file
FileOutputStream file = new FileOutputStream("path/to/excel/file.xlsx");
workbook.write(file);
// Close the file
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Make sure to replace "path/to/excel/file.xlsx" with the actual path to your Excel file.
These examples demonstrate the basic reading and writing operations using Apache POI. You can further explore the API documentation to work with more advanced features such as formatting, formulas, and multiple sheets within an Excel file.