1. 在項(xiàng)目中添加Maven依賴
首先,在你的Maven項(xiàng)目的pom.xml文件中添加以下依賴:
<dependencies>
<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>
</dependencies>這樣就會將Apache Poi庫添加到你的項(xiàng)目中。
2. 創(chuàng)建Excel文檔
要創(chuàng)建一個新的Excel文檔,可以使用以下代碼:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelCreator {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
workbook.write(outputStream);
}
}
}上述代碼創(chuàng)建了一個新的Excel文檔,添加了一個名為"Sheet1"的工作表,并在第一行第一列寫入了"Hello, World!",最后將文檔保存到output.xlsx文件中。
3. 讀取Excel文檔
要讀取一個現(xiàn)有的Excel文檔,可以使用以下代碼:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
public class ExcelReader {
public static void main(String[] args) throws Exception {
try (FileInputStream inputStream = new FileInputStream("input.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String value = cell.getStringCellValue();
System.out.println(value);
}
}
}上述代碼打開名為input.xlsx的Excel文檔,并讀取第一個工作表的第一行第一列的值,并將其打印出來。
4. 修改Excel文檔
要修改一個Excel文檔,可以使用以下代碼:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ExcelModifier {
public static void main(String[] args) throws Exception {
try (FileInputStream inputStream = new FileInputStream("input.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
cell.setCellValue("Hello, Apache Poi!");
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
workbook.write(outputStream);
}
}
}
}上述代碼打開名為input.xlsx的Excel文檔,修改第一個工作表的第一行第一列的值為"Hello, Apache Poi!",并將修改后的文檔保存到output.xlsx文件中。
5. 其他操作
除了上述介紹的基本操作外,Apache Poi庫還提供了許多其他功能,如合并單元格、設(shè)置字體樣式、設(shè)置邊框和背景顏色等。你可以使用官方文檔和示例代碼來學(xué)習(xí)和掌握這些功能。
6. 注意事項(xiàng)
在使用Apache Poi庫時(shí),需要注意以下幾點(diǎn):
確保所使用的Poi庫版本與所依賴的其他庫版本兼容。
避免在大規(guī)模數(shù)據(jù)處理時(shí)頻繁創(chuàng)建和寫入Excel文檔,以免導(dǎo)致性能問題。
及時(shí)關(guān)閉打開的文件流,以釋放資源。
總結(jié)
通過本文,我們了解了如何在Maven項(xiàng)目中引用Apache Poi庫,并學(xué)習(xí)了如何創(chuàng)建、讀取和修改Excel文檔。希望本文能夠幫助你在Java應(yīng)用程序中輕松使用Apache Poi庫進(jìn)行Excel文檔的操作。