在Java中实现Excel导入和导出功能,我们可以依赖像Apache POI这样的库,它是处理Microsoft Office文档格式的Java API。Apache POI支持老式的Excel格式(HSSF)和新式的Excel格式(XSSF)。下面是利用Apache POI进行Excel文件导入(读取)和导出(写入)的基本示例。
添加Apache POI依赖
首先,你需要在项目的pom.xml
中添加Apache POI的依赖(如果你使用Maven来构建项目):
<dependencies>
<!-- Apache POI dependency for Excel manipulation -->
<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>
请确保使用最新版本的Apache POI。
导出数据到Excel文件
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelExporter {
public static void main(String[] args) throws IOException {
// 创建一个Excel工作簿
Workbook workbook = new XSSFWorkbook();
// 创建一个工作表sheet
Sheet sheet = workbook.createSheet("Sample sheet");
// 创建数据
Object[][] bookData = {
{"Head First Java", "Kathy Serria", 79},
{"Effective Java", "Joshua Bloch", 36},
{"Clean Code", "Robert Martin", 42},
{"Thinking in Java", "Bruce Eckel", 35},
};
int rowCount = 0;
for (Object[] aBook : bookData) {
Row row = sheet.createRow(++rowCount);
int columnCount = 0;
for (Object field : aBook) {
Cell cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try (FileOutputStream outputStream = new FileOutputStream("Books.xlsx")) {
workbook.write(outputStream);
}
// 关闭工作簿
workbook.close();
}
}
从Excel文件导入数据
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExcelImporter {
public static void main(String[] args) throws IOException {
// 文件位置
String excelFilePath = "Books.xlsx";
// 创建一个工作簿对象
InputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
// 读取数据
for (Row nextRow : firstSheet) {
for (Cell nextCell : nextRow) {
if (nextCell.getCellType() == CellType.STRING) {
System.out.print(nextCell.getStringCellValue());
} else if (nextCell.getCellType() == CellType.NUMERIC) {
System.out.print(nextCell.getNumericCellValue());
}
System.out.print(" - ");
}
System.out.println();
}
// 关闭工作簿及文件流
workbook.close();
inputStream.close();
}
}
上述代码片段演示了如何使用Apache POI库来创建一个简单的Excel文件,以及如何读取该文件的内容。对于更复杂的Excel操作,比如样式、公式、数据验证等,Apache POI提供了广泛的API来处理这些需求。
请注意,为了处理大型的Excel文件,Apache POI提供了SXSSF API,它是XSSF的流式版本,能够处理大型数据集,而不会消耗大量的内存。此外,对于读取操作,你还可以使用Event API来降低内存消耗。