当前位置: 首页 > article >正文

Apache POI,springboot中导出excel报表

2. Apache POI

2.1 介绍

Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。
一般情况下,POI 都是用于操作 Excel 文件。

Apache POI 的应用场景:

  • 银行网银系统导出交易明细

  • 各种业务系统导出Excel报表

  • 批量导入业务数据

入门案例

Apache POI既可以将数据写入Excel文件,也可以读取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>

2.2.1 将数据写入Excel文件

1). 代码开发

package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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();
    }
}

2). 实现效果

在D盘中生成itcast.xlsx文件,创建名称为itcast的Sheet页,同时将内容成功写入。

2.2.2 读取Excel文件中的数据

1). 代码开发

package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class POITest {
    /**
     * 基于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();
    }
}

2). 实现效果

将itcast.xlsx文件中的数据进行读取

3. 导出运营数据Excel报表

3.1controller层

	/**
     * 导出运营数据报表
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("导出运营数据报表")
    public void export(HttpServletResponse response){
        reportService.exportBusinessData(response);
    }

3.2service层

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据,提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        /**
         class.getResourceAsStream
         如果path不带"/",那么就是从当前class文件的路径下找文件
         如果path带"/",那么就是从类路径.classpath中去找文件
         */
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                if (Objects.isNull(businessData.getTurnover())){
                    row.getCell(2).setCellValue(0.0);
                }else {
                    row.getCell(2).setCellValue(businessData.getTurnover());
                }
                if (Objects.isNull(businessData.getValidOrderCount())){
                    row.getCell(3).setCellValue(0);
                }else {
                    row.getCell(3).setCellValue(businessData.getValidOrderCount());
                }
                if (Objects.isNull(businessData.getOrderCompletionRate())){
                    row.getCell(4).setCellValue(0.0);
                }else {
                    row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                }
                if (Objects.isNull(businessData.getUnitPrice())){
                    row.getCell(5).setCellValue(0.0);
                }else {
                    row.getCell(5).setCellValue(businessData.getUnitPrice());
                }
                if (Objects.isNull(businessData.getNewUsers())){
                    row.getCell(6).setCellValue(0);
                }else {
                    row.getCell(6).setCellValue(businessData.getNewUsers());
                }
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }

http://www.kler.cn/news/17239.html

相关文章:

  • Websocket的基本认识、使用与封装
  • JavaScript:数组---二分法
  • 【笔试强训选择题】Day7.习题(错题)解析
  • 看我如何通过帮助服务台轻松黑掉数百家公司
  • selenium自动化面试题回答
  • KeepAlived高可用环境搭建
  • JavaScript:二叉树(层序遍历)
  • Python | 人脸识别系统 — 人脸识别
  • Linux线程:互斥锁mutex的使用
  • 什么是Spring FactoryBean?有什么作用?
  • ES6:promise简单学习
  • 从MultipartFile上传文件名乱码开始详解编解码知识
  • 2023年会展服务研究报告
  • DDD系列:二、应用架构设计演变
  • 初识WebAssembly
  • 京东T7架构师用470页就把微服务架构原理与开发实战文档讲完了
  • 【华为OD机试 2023最新 】递增字符串(C语言题解 100%)
  • 第二章--第一节--什么是语言生成
  • 【51单片机】数码管显示(样例展示以及异常分析)
  • Camtasia2023最好用的电脑屏幕录制软件
  • 11 | Qt的日志
  • 【UE】高级载具插件-04-坦克瞄准开火
  • mysql索引和事务
  • 很佩服的一个Google大佬,离职了。。
  • 1. 先从云计算讲起
  • NEWS|关于人工智能大型语言模型能否理解的争论
  • Allegro自定义快捷键(修改 ix iy 的步进,其他快捷功能)
  • 计算机视觉介绍
  • React初识
  • 怎么衡量纸白银走势图的强弱?