Java 读写 Excel 表格(最常用方案:Apache POI)
Java 操作 Excel 最主流、稳定的方案是 Apache POI,同时支持 .xls(Excel 2003) 和 .xlsx(Excel 2007+) 两种格式。
我直接给你完整可运行的代码,复制就能用,附带详细注释。
一、先引入依赖(Maven/Gradle)
Maven(最常用)
在 pom.xml 中添加:
xml
<!-- Excel 2007+ .xlsx 格式 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- Excel 2003 .xls 格式(可选) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.5</version>
</dependency>
Gradle
groovy
implementation 'org.apache.poi:poi-ooxml:5.2.5'
implementation 'org.apache.poi:poi:5.2.5'
二、Java 写入 Excel(.xlsx)
完整代码
java
运行
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWrite {
public static void main(String[] args) {
// 1. 创建一个新的工作簿(.xlsx 用 XSSFWorkbook)
try (Workbook workbook = new XSSFWorkbook()) {
// 2. 创建工作表
Sheet sheet = workbook.createSheet("用户信息表");
// 3. 创建表头行(第0行)
Row headerRow = sheet.createRow(0);
// 设置表头单元格
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("姓名");
headerRow.createCell(2).setCellValue("年龄");
headerRow.createCell(3).setCellValue("城市");
// 4. 写入数据行(第1、2、3行)
Object[][] data = {
{1, "张三", 22, "北京"},
{2, "李四", 25, "上海"},
{3, "王五", 28, "广州"}
};
for (int i = 0; i < data.length; i++) {
Row row = sheet.createRow(i + 1);
Object[] rowData = data[i];
for (int j = 0; j < rowData.length; j++) {
row.createCell(j).setCellValue(rowData[j].toString());
}
}
// 5. 自动调整列宽
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
// 6. 写入文件
try (FileOutputStream fos = new FileOutputStream("user.xlsx")) {
workbook.write(fos);
System.out.println("Excel 写入成功!文件路径:当前项目根目录");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、Java 读取 Excel(.xlsx)
完整代码
java
运行
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelRead {
public static void main(String[] args) {
// 要读取的文件路径
String filePath = "user.xlsx";
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 获取最后一行的行号
int lastRowNum = sheet.getLastRowNum();
// 遍历行(跳过表头从第1行开始,从0开始则包含表头)
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
if (row == null) continue;
// 读取单元格数据
String id = getCellValue(row.getCell(0));
String name = getCellValue(row.getCell(1));
String age = getCellValue(row.getCell(2));
String city = getCellValue(row.getCell(3));
System.out.println("ID:" + id + ",姓名:" + name + ",年龄:" + age + ",城市:" + city);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 工具方法:统一获取单元格的值(处理不同类型)
private static String getCellValue(Cell cell) {
if (cell == null) return "";
switch (cell.getCellType()) {
case STRING: return cell.getStringCellValue();
case NUMERIC: return String.valueOf((int) cell.getNumericCellValue());
case BOOLEAN: return String.valueOf(cell.getBooleanCellValue());
default: return "";
}
}
}
四、关键说明
- 格式区分
.xlsx(2007+):XSSFWorkbook.xls(2003):HSSFWorkbook
- 行和列都是从 0 开始计数
- 大文件处理超大数据量(10 万 + 行)推荐使用 SXSSFWorkbook,避免内存溢出。
- 异常处理代码中使用了
try-with-resources,自动关闭流,最安全。
五、运行效果
- 写入:生成
user.xlsx,包含表头 + 3 行数据 - 读取:控制台打印:
plaintext
ID:1,姓名:张三,年龄:22,城市:北京 ID:2,姓名:李四,年龄:25,城市:上海 ID:3,姓名:王五,年龄:28,城市:广州
总结
- 用 Apache POI 是 Java 操作 Excel 的标准方案
- 写入用
XSSFWorkbook+createRow/createCell - 读取用
getSheetAt+ 遍历行 + 工具方法取值 - 代码直接复制运行,无需修改
4951

被折叠的 条评论
为什么被折叠?



