Apache POI操作Excel详解

Maven依赖

XML 复制代码
<!-- 核心库(支持.xls) -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
</dependency>

<!-- 支持.xlsx格式 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
</dependency>

核心概念

类名 作用 对应格式
SXSSFWorkbook 大数据量导出(流式处理) .xlsx
Sheet 工作表 通用
Row 行 通用
Cell 单元格 通用

基础操作

java 复制代码
private void test() {
        //创建工作簿
		Workbook workbook = new SXSSFWorkbook();
		Sheet sheet = workbook.createSheet();

		//创建表头
        //创建第一行
		Row row = sheet.createRow(0);
        //第一行 第一列
		row.createCell(0).setCellValue("姓名");
        //第一行 第二列
		row.createCell(1).setCellValue("年龄");

        //创建第二行
		Row row1 = sheet.createRow(1);
        //第二行 第一列
		row1.createCell(0).setCellValue("张三");
        //第二行 第二列
		row1.createCell(1).setCellValue("18");

        //创建第三行
		Row row2 = sheet.createRow(2);
        //第三行 第一列
		row2.createCell(0).setCellValue("李四");
        //第三行 第二列
		row2.createCell(1).setCellValue("20");

		try (FileOutputStream fileOutputStream = new FileOutputStream("学生信息.xlsx")) {
			workbook.write(fileOutputStream);
            workbook.close();
		} catch (Exception e) {
            throw new RuntimeException();
		}
	}

封装工具类使用 ExcelUtils

读取文件

java 复制代码
ExcelUtils.read(OPCPackage.open(inputStream), 1, (row, index) -> {
	String keyword = ExcelUtils.getString(row.getCell(0));
	String cityName = ExcelUtils.getString(row.getCell(1));
	String positionType = ExcelUtils.getString(row.getCell(2));
	if (StringUtils.isEmpty(keyword) || "未匹配到城市".equals(cityName) || "未匹配到工种".equals(positionType)) {
		return;
	}
	PositionSeoKeywordRequest keywordRequest = PositionSeoKeywordRequest.builder().keyword(keyword)
			.positionType(positionType).cityName(cityName)
			.deleted(0L).createTime(now).updateTime(now).build();
	list.add(keywordRequest);
});

写文件

java 复制代码
//创建工作簿实例
Workbook workbook = new SXSSFWorkbook();
// sheet页1-拉新业务看板数据
int sheet1Volume = ExcelUtils.write(
	workbook,
	(page, size) -> this.customerShareRelationRecordService.listCustomerShareSummaries(
			param.getPeriod(), param.getSharerId(), Paging.of(page, size)
	),
	(row, summary, i) -> {
		EmployeeDTO employee = employeesMap.get(summary.getSharerId());
		// sharerId = 0 代表是合计总数
		row.createCell(0).setCellValue(
				summary.getSharerId() == 0L ? "合计" : employee == null ? null : employee.getName()
		);
		row.createCell(1).setCellValue(employee == null ? null : employee.getMobile());
		row.createCell(2).setCellValue(summary.getRegisterCount());
		row.createCell(3).setCellValue(
				summary.getReleasePositionNormalCount() + summary.getReleasePositionAbnormalCount()
		);
		row.createCell(4).setCellValue(summary.getReleasePositionNormalCount());
		row.createCell(5).setCellValue(summary.getReleasePositionAbnormalCount());
	},
	"销售人员", "手机号", "注册人数", "发布职位人数", "发布职位人数-正常用户", "发布职位人数-异常用户"
);
workbook.setSheetName(0, "汇总数据");

// sheet页2-异常用户明细数据
int sheet2Volume = ExcelUtils.write(
	workbook,
	(page, size) -> this.customerShareRelationRecordService.listEachTypeUsers(
			param.getPeriod(), param.getSharerId(), Paging.of(page, size), CustomerShareType.ABNORMAL
	),

	(row, abnormal, i) -> {
		EmployeeDTO employee = employeesMap.get(abnormal.getSharerId());
		row.createCell(0).setCellValue(ObjectUtils.ifNull(employee, EmployeeDTO::getName));
		row.createCell(1).setCellValue(abnormal.getMobile());
		row.createCell(2).setCellValue(DateUtils.format(abnormal.getOperateTime()));
		row.createCell(3).setCellValue(abnormal.getAbnormalMobile());
	},
	"销售人员", "用户登录手机号", "发布职位日期", "发布职位信息填写联系电话"
);
workbook.setSheetName(1, "发布职位人-异常用户明细");

// sheet页3-正常用户明细数据
int sheet3Volume = ExcelUtils.write(
	workbook,
	(page, size) -> this.customerShareRelationRecordService.listEachTypeUsers(
			param.getPeriod(), param.getSharerId(), Paging.of(page, size), CustomerShareType.NORMAL
	),

	(row, abnormal, i) -> {
		EmployeeDTO employee = employeesMap.get(abnormal.getSharerId());
		row.createCell(0).setCellValue(ObjectUtils.ifNull(employee, EmployeeDTO::getName));
		row.createCell(1).setCellValue(abnormal.getMobile());
		row.createCell(2).setCellValue(DateUtils.format(abnormal.getOperateTime()));
		row.createCell(3).setCellValue(abnormal.getAbnormalMobile());
	},
	"销售人员", "用户登录手机号", "发布职位日期", "发布职位信息填写联系电话"
);
workbook.setSheetName(2, "发布职位人-正常用户明细");

// 保存文件
File attachment = new File(this.getExportDirectory(), String.valueOf(exportationId));
try (OutputStream output = new FileOutputStream(attachment)) {
workbook.write(output);
workbook.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//导出完成
this.exportationService.completeExporting(exportationId, sheet1Volume + sheet2Volume + sheet3Volume);
java 复制代码
private File doExportRecruitData(List<PositionEmailSendDTO> positionEmailSendDTOS) {
	File attachment = new File(getExportDirectory(), UUID.randomUUID() + EXCEL_EXTENSION);
	try (Workbook workbook = new SXSSFWorkbook()) {
		Sheet sheet = ExcelUtils.initializeSheet(workbook,EXCEL_HEADERS);
		for (int i = 0, size = positionEmailSendDTOS.size(); i < size; i++) {
			PositionEmailSendDTO label = positionEmailSendDTOS.get(i);
			Row row = sheet.createRow(i+1);
			row.createCell(0).setCellValue(label.getTitle());
			row.createCell(1).setCellValue(label.getDescription());
			row.createCell(2).setCellValue(label.getRegionName());
			row.createCell(3).setCellValue(label.getType().getDescription());
			row.createCell(4).setCellValue(label.getMobile());
		}
		try (OutputStream output = new FileOutputStream(attachment)) {
			workbook.write(output);
			workbook.close();
		}
		return attachment;
	} catch (Exception e) {
		log.error("【招聘数据邮件发送定时器】导出失败:{}",e.getMessage());
		throw new RuntimeException("Failed to export recruitment data", e);
	}
}
相关推荐
别动我齐刘海1 小时前
C++ 工程化学习
java·linux·前端·c++·学习·机器学习·机器人
code2cat2 小时前
Java进阶篇之AtomicLongFieldUpdater:把累计额度留在对象字段中
java·cas·并发编程
WeiXin_DZbishe2 小时前
基于springboot城市公交实时运营与调度系统-计算机毕设 附源码【课程设计】66173
java·vue.js·spring boot·后端·python·php·课程设计
泡茶喝茶写代码2 小时前
A股量化数据工程:从 REST 接口到策略信号(第 18 篇):放量缩量异动扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
wewowilling2 小时前
认识微服务
java·运维·微服务·springcloud
代码什么用3 小时前
Java Web 7-10
java·servlet
蜗牛互联网4 小时前
GPT-6 与 Intelligent UI:从回答到可审计操作的产品迁移
java·人工智能·后端
SL_staff5 小时前
运维救火实录:钉钉考勤API变更引发工资计算异常,我们用JVS-Logic可视化逻辑引擎实现分钟级热修复
java·mysql·全栈
SunnyDays10115 小时前
Java 查找并高亮 Word 文字:精确查找及正则表达式模糊查找
java·查找文字·word 文档·高亮文字·正则匹配查找·模糊查找