Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。
入门案例
Apache POI的maven坐标:(项目中已导入)
<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文件
public class POITest {
/**
* 基于POI向Excel文件写入数据
* @throws Exception
*/
public static void write() throws Exception{
//在内存中创建一个Excel文件对象
XSSFWorkbook excel = new XSSFWorkbook();
//创建Sheet页
XSSFSheet sheet = excel.createSheet("itcast");
//在Sheet页中创建行,0表示第1行
XSSFRow row1 = sheet.createRow(0);
//创建单元格并在单元格中设置值,单元格编号也是从0开始,1表示第2个单元格
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
XSSFRow row2 = sheet.createRow(1);
row2.createCell(1).setCellValue("张三");
row2.createCell(2).setCellValue("北京");
XSSFRow row3 = sheet.createRow(2);
row3.createCell(1).setCellValue("李四");
row3.createCell(2).setCellValue("上海");
FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
//通过输出流将内存中的Excel文件写入到磁盘上
excel.write(out);
//关闭资源
out.flush();
out.close();
excel.close();
}
public static void main(String[] args) throws Exception {
write();
}
}
效果
读取Excel文件中的数据
/**
* 基于POI读取Excel文件
* @throws Exception
*/
public static void read() throws Exception{
FileInputStream in = new FileInputStream(new File("D:\\itcast.xlsx"));
//通过输入流读取指定的Excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取Excel文件的第1个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取Sheet页中的最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
//获取Sheet页中的行
XSSFRow titleRow = sheet.getRow(i);
//获取行的第2个单元格
XSSFCell cell1 = titleRow.getCell(1);
//获取单元格中的文本内容
String cellValue1 = cell1.getStringCellValue();
//获取行的第3个单元格
XSSFCell cell2 = titleRow.getCell(2);
//获取单元格中的文本内容
String cellValue2 = cell2.getStringCellValue();
System.out.println(cellValue1 + " " +cellValue2);
}
//关闭资源
in.close();
excel.close();
}
public static void main(String[] args) throws Exception {
read();
}
效果
实战实例,苍穹外卖订单导出
/**
* 导出运营报表
*/
@GetMapping("/export")
@ApiOperation("导出运营数据报表")
public void export(HttpServletResponse response){
reportService.exportBusinessData(response);
}
@Override
public void exportBusinessData(HttpServletResponse response) {
//查出三十天的汇总数据
LocalDateTime endTime = LocalDateTime.now();
//减去三十天,的零分
LocalDateTime startTime = endTime.minusDays(30).toLocalDate().atStartOfDay();
BusinessDataVO businessDataVO = workspaceService.businessData(startTime,endTime);
log.info("businessDataVO: {}",businessDataVO.toString());
//查询每一天的明细数据
ArrayList<BusinessDataVO> dayVoList = new ArrayList<>();
while(startTime.isBefore(endTime)){
LocalDateTime end = startTime.plusHours(24).minusSeconds(1);
BusinessDataVO dataVo = workspaceService.businessData(startTime, end);
dayVoList.add(dataVo);
log.info("startTime: {},dayVo: {}",startTime,dataVo);
startTime = startTime.plusDays(1);
}
//
try{
// 读取excel模板
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// 填充模板
XSSFSheet sheet = workbook.getSheetAt(0);
// 填充30天的汇总数据
XSSFRow row3 = sheet.getRow(3);
XSSFRow row4 = sheet.getRow(4);
row3.getCell(2).setCellValue(businessDataVO.getTurnover()+"");
row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate()+"");
row3.getCell(6).setCellValue(businessDataVO.getNewUsers()+"");
row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount()+"");
row4.getCell(4).setCellValue(businessDataVO.getUnitPrice()+"");
// 填充某一天的汇总数据
int i= 0;
startTime = endTime.minusDays(30).toLocalDate().atStartOfDay();
for (BusinessDataVO dayVo : dayVoList) {
XSSFRow row = sheet.getRow(7 + i);
if(row == null){
row = sheet.createRow(7 + i);
row.createCell(1);
row.createCell(2);
row.createCell(3);
row.createCell(4);
row.createCell(5);
row.createCell(6);
}
row.getCell(1).setCellValue(startTime.toLocalDate().toString());
row.getCell(2).setCellValue(dayVo.getTurnover()+"");
row.getCell(3).setCellValue(dayVo.getValidOrderCount()+"");
row.getCell(4).setCellValue(dayVo.getOrderCompletionRate()+"");
row.getCell(5).setCellValue(dayVo.getUnitPrice()+"");
row.getCell(6).setCellValue(dayVo.getNewUsers()+"");
i++;
startTime=startTime.plusDays(1);
}
// 写入到response的输出流
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
// 关闭流
workbook.close();
outputStream.close();
}catch (Exception e) {
log.error(e.getMessage(), e);
throw new BaseException("文件下载异常");
}
导出效果