发布于2026-05-30 阅读(0)
扫一扫,手机访问
在Ja va开发里操作Excel文件,主流方案无非两条路:
这次我们重点啃下Apache POI这块硬骨头,手把手带你掌握Ja va操作Excel的核心技能。
很多人一开始会想:直接用Ja va的IO流读写Excel行不行?答案是——行不通。用字符流去读Excel文件,读出来的要么是乱码,要么直接报错,根本拿不到表里的数据。二进制流倒是能实现文件拷贝,但想解析内容?想都别想。
// 错误演示:用字符流读取Excel文件
import ja va.io.FileReader;
import ja va.io.BufferedReader;
import ja va.io.IOException;
public class WrongExcelReaderDemo {
public static void main(String[] args) {
// 待读取的Excel文件路径(.xls或.xlsx均可,都会报错/乱码)
String excelFilePath = "src/test/ja va/Demo.xlsx";
// 声明字符流对象
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
// 1. 初始化字符流,尝试读取Excel文件
fileReader = new FileReader(excelFilePath);
bufferedReader = new BufferedReader(fileReader);
// 2. 按行读取文件内容
String line;
System.out.println("尝试用字符流读取Excel文件内容:");
while ((line = bufferedReader.readLine()) != null) {
// 3. 输出读取到的内容(会是乱码或无法解析的字符)
System.out.println(line);
}
} catch (IOException e) {
// 捕获IO异常(可能直接抛出文件读取失败,或读取过程中报错)
e.printStackTrace();
} finally {
// 4. 手动关闭流(避免资源泄露,即使读取失败也执行)
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

说到底,直接用IO流干不了这活儿,它只适合做文件级别的搬运工。
Apache POI,全称Poor Obfuscation Implementation,听起来挺拗口,其实就是Apache给Ja va开发者提供的一套操作Microsoft Office文档的API。Excel、Word、PowerPoint,通通能搞定。
Excel分两种老式和新式格式,区别很明显:
选哪个格式,决定了你该用POI的哪个子模块。
操作不同格式需要引入不同的依赖,顺手把版本也定好:
org.apache.poi poi 5.2.4 org.apache.poi poi-ooxml 5.2.4

理论说再多不如动手写个例子。下面咱们就实操一下,用POI写一个实习记录表。
HSSFWorkbook:对应.xls格式XSSFWorkbook:对应.xlsx格式import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import ja va.io.FileOutputStream;
import ja va.io.IOException;
// 生成实习记录Excel文件(.xls格式)
public class Test {
public static void main(String[] args) throws Exception {
// 1. 创建Workbook(HSSFWorkbook对应.xls,XSSFWorkbook对应.xlsx)
Workbook workbook = new HSSFWorkbook();
// 2. 创建Sheet,命名为「实习记录」(核心修改点1)
Sheet sheet = workbook.createSheet("实习记录");
// 3. 创建表头行(第一行,索引0)
Row headerRow = sheet.createRow(0);
// 表头单元格:姓名、性别、工作、公司
headerRow.createCell(0).setCellValue("姓名");
headerRow.createCell(1).setCellValue("性别");
headerRow.createCell(2).setCellValue("工作");
headerRow.createCell(3).setCellValue("公司");
// 4. 创建数据行(第二行,索引1),填充指定数据(核心修改点2)
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue("小当家"); // 姓名
dataRow.createCell(1).setCellValue("男"); // 性别
dataRow.createCell(2).setCellValue("后端开发");// 工作
dataRow.createCell(3).setCellValue("xxx"); // 公司
// 5. 自动调整列宽(优化显示效果)
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
// 6. 写入文件并关闭资源
try (FileOutputStream fos = new FileOutputStream("D:\实习记录.xls")) {
workbook.write(fos);
System.out.println("实习记录Excel生成成功!路径:D:\实习记录.xls");
} catch (IOException e) {
e.printStackTrace();
} finally {
workbook.close();
}
}
}
跑完这段代码,D盘下就会冒出一个"实习记录.xls",打开看看:

控制台可能报个日志相关的警告,别慌,那是缺少log4j依赖,不影响demo跑通。

写出来是为了读。接下来看看怎么把刚才生成的Excel数据读回Ja va中。
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import ja va.io.FileInputStream;
import ja va.io.InputStream;
public class TestRead {
public static void main(String[] args) throws Exception {
// 获取文件的数据流(实习记录Excel路径)
InputStream inputStream = new FileInputStream("D:\实习记录.xls");
// 创建文件对象(仅支持.xls格式)
Workbook workbook = new HSSFWorkbook(inputStream);
// 获取Sheet(按索引取第一个Sheet)
Sheet sheet = workbook.getSheetAt(0);
// ========== 读取小当家的信息 ==========
// 读取第二行(数据行,索引1):第一行是表头(索引0)
Row dataRow = sheet.getRow(1);
// 读取“姓名”列(第二行第一列,索引0)
Cell nameCell = dataRow.getCell(0);
String name = nameCell.getStringCellValue();
// 读取“性别”列(第二行第二列,索引1)
Cell genderCell = dataRow.getCell(1);
String gender = genderCell.getStringCellValue();
// 读取“工作”列(第二行第三列,索引2)
Cell jobCell = dataRow.getCell(2);
String job = jobCell.getStringCellValue();
// 读取“公司”列(第二行第四列,索引3)
Cell companyCell = dataRow.getCell(3);
String company = companyCell.getStringCellValue();
// 打印读取结果
System.out.println("姓名:" + name);
System.out.println("性别:" + gender);
System.out.println("工作:" + job);
System.out.println("公司:" + company);
// 关闭流
inputStream.close();
}
}

实际开发里,单元格不会全是字符串——数字、日期甚至公式都有可能。如果你一股脑用getStringCellValue()去取数字单元格,程序会直接报错。所以必须根据单元格类型来做分支处理:
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import ja va.io.FileInputStream;
import ja va.io.InputStream;
public class TestRead {
public static void main(String[] args) throws Exception {
// 获取文件的数据流(实习记录Excel路径)
InputStream inputStream = new FileInputStream("D:\实习记录.xls");
// 创建文件对象(仅支持.xls格式)
Workbook workbook = new HSSFWorkbook(inputStream);
// 获取Sheet(按索引取第一个Sheet)
Sheet sheet = workbook.getSheetAt(0);
// ========== 读取小当家的信息 ==========
// 读取第二行(数据行,索引1):第一行是表头(索引0)
Row dataRow = sheet.getRow(1);
// 读取“姓名”列(第二行第一列,索引0)
Cell nameCell = dataRow.getCell(0);
String name = nameCell.getStringCellValue();
// 读取“性别”列(第二行第二列,索引1)
Cell genderCell = dataRow.getCell(1);
String gender = genderCell.getStringCellValue();
// 读取“工作”列(第二行第三列,索引2)
Cell jobCell = dataRow.getCell(2);
if (jobCell.getCellType() == CellType.STRING) {
String job = jobCell.getStringCellValue();
} else if (jobCell.getCellType() == CellType.NUMERIC) {
double jobNum = jobCell.getNumericCellValue();
String job = String.valueOf(jobNum);
}
// 读取“公司”列(第二行第四列,索引3)
Cell companyCell = dataRow.getCell(3);
if (companyCell.getCellType() == CellType.STRING) {
String company = companyCell.getStringCellValue();
} else if (companyCell.getCellType() == CellType.NUMERIC) {
double companyNum = companyCell.getNumericCellValue();
String company = String.valueOf(companyNum);
}
// 打印读取结果
System.out.println("姓名:" + name);
System.out.println("性别:" + gender);
System.out.println("工作:" + job);
System.out.println("公司:" + company);
// 关闭流
inputStream.close();
}
}
走完这一趟,可以捋一下学到的东西:
POI功能全面但代码量偏大,如果只是想快速处理大批量数据,EasyExcel封装得更友好。不过理解POI的底层逻辑,对日后用任何Excel工具都有帮助——毕竟,万变不离其宗。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8