Apache POI案例代碼詳解:輕松操作Excel文件
Apache POI是一個強大的Java庫,用于處理Microsoft Office文件,尤其是Excel文件。本文將通過實際案例,詳細講解如何使用Apache POI來操作Excel文件。
1. 環(huán)境準備
在開始使用Apache POI之前,需要在項目中添加相關(guān)依賴。可以通過Maven或Gradle來管理依賴:
<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>
2. 創(chuàng)建新的Excel文件
以下代碼展示了如何創(chuàng)建一個新的Excel文件并添加數(shù)據(jù):
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, Apache POI!");
try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
workbook.write(outputStream);
}
3. 讀取Excel文件
下面的代碼演示了如何讀取現(xiàn)有的Excel文件:
Workbook workbook = WorkbookFactory.create(new File("example.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.toString() + "t");
}
System.out.println();
}
4. 設(shè)置單元格樣式
Apache POI允許我們?yōu)閱卧裨O(shè)置各種樣式,如下所示:
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 14);
style.setFont(font);
cell.setCellStyle(style);
5. 處理不同類型的數(shù)據(jù)
Apache POI支持多種數(shù)據(jù)類型的處理:
Cell cell = row.createCell(0);
cell.setCellValue("文本");
cell = row.createCell(1);
cell.setCellValue(123.45);
cell = row.createCell(2);
cell.setCellValue(true);
cell = row.createCell(3);
cell.setCellValue(new Date());
結(jié)語
通過以上案例,我們可以看到Apache POI提供了豐富的API來操作Excel文件。無論是創(chuàng)建新文件、讀取現(xiàn)有文件,還是設(shè)置樣式和處理不同類型的數(shù)據(jù),Apache POI都能輕松應(yīng)對。在實際開發(fā)中,這些功能可以大大提高處理Excel文件的效率。