Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。
业务场景:导入Excel文件内数据到数据库内、把数据库内的数据导出为Excel报表。
maven坐标
java
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
将数据写入Excel文件示例
java
@Test
public void testApachePOI(){
//在内存中创建一个Excel对象
XSSFWorkbook excel = new XSSFWorkbook();
//创建Shell页
XSSFSheet sheet = excel.createSheet("itcast");
//在Sheet页中创建行,0为第一行,关于ApachePOI的行和列都是从0开始
XSSFRow row = sheet.createRow(0);
//创建单元格,0为第一列
row.createCell(0).setCellValue("编号");
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("年龄");
//创建数据行
XSSFRow dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(1);
dataRow.createCell(1).setCellValue("张三");
dataRow.createCell(2).setCellValue(18);
//创建数据行
XSSFRow dataRow2 = sheet.createRow(2);
dataRow2.createCell(0).setCellValue(2);
dataRow2.createCell(1).setCellValue("张四");
dataRow2.createCell(2).setCellValue(19);
//创建输出流,指定路径
FileOutputStream out = null;
try {
out = new FileOutputStream("D:\\excel\\test.xlsx");
excel.write(out);
}catch (Exception e){
e.printStackTrace();
}finally {
if (excel != null){
try {
excel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (out != null){
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
文档

读取excel的数据

java
@Test
public void testApachePOI2() throws Exception{
FileInputStream in = new FileInputStream("D:\\excel\\test.xlsx");
//通过输入流读取指定的文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取第一个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
int LastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= LastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
if (i==0){
System.out.println(row.getCell(0).getStringCellValue()+","+row.getCell(1).getStringCellValue()+","+row.getCell(2).getStringCellValue());
}
else {
System.out.println(row.getCell(0)+","+row.getCell(1).getStringCellValue()+","+row.getCell(2));
}
}
in.close();
excel.close();
}
实战:在用报表模板创建三十天营业额统计
Controller层
java
@GetMapping("/export")
@ApiOperation("导出数据")
public Result exportData(HttpServletResponse response){
log.info("开始导出数据...");
reportService.exportData(response);
return null;
}
Service层
java
/**
* 导出近30天的运营数据报表
* @param response
*/
@Override
public void exportData(HttpServletResponse response) {
LocalDate now = LocalDate.now();
LocalDate begin = now.minusDays(30);
LocalDate end = now.minusDays(1);
//查询运营数据
BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
LocalDateTime.of(end, LocalTime.MAX));
//读取模板,将其作为输入流读取到内存中
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("template/运营数据报表模板.xlsx");
try {
XSSFWorkbook excel = new XSSFWorkbook(inputStream);
XSSFSheet sheet = excel.getSheet("Sheet1");
sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
//获取第四行
XSSFRow row4 = sheet.getRow(3);
row4.getCell(2).setCellValue(businessDataVO.getTurnover());
row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
//获取第五行
XSSFRow row5 = sheet.getRow(4);
row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());
//明细数据
for (int i=0;i<30;i++){
LocalDate date = begin.plusDays(i);
businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),
LocalDateTime.of(date, LocalTime.MAX));
XSSFRow row = sheet.getRow(i+7);
row.getCell(1).setCellValue(date.toString());
row.getCell(2).setCellValue(businessDataVO.getTurnover());
row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
row.getCell(6).setCellValue(businessDataVO.getNewUsers());
}
//通过输出流进行文件下载到客户端服务器中
OutputStream outputStream = response.getOutputStream();
excel.write(outputStream);
outputStream.close();
excel.close();
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
模板放在
所以可以通过获取类->获取类加载器->获取resource->路径获得。
BusinessDataVO
java
package com.sky.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 数据概览
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BusinessDataVO implements Serializable {
private Double turnover;//营业额
private Integer validOrderCount;//有效订单数
private Double orderCompletionRate;//订单完成率
private Double unitPrice;//平均客单价
private Integer newUsers;//新增用户数
}
模板

导出示例

补充:
HttpServletResponse 属于 Java Servlet API 框架的一部分。
框架介绍
所属框架: Java Servlet API(Java EE/Web容器标准API)
作用: 用于处理HTTP响应的核心接口
相关方法说明
在当前代码中使用的 HttpServletResponse 方法包括:
getOutputStream() - 获取响应的输出流,用于向客户端发送二进制数据(如Excel文件)
setContentType() - 设置响应内容类型(MIME类型)
setHeader() - 设置HTTP响应头信息