【项目实战 Day12】springboot + vue 苍穹外卖系统(Apache POI + 工作台模块 + Excel表格导出 完结)

目录

一、工作台模块

[1、查询今日运营数据 - GET接口](#1、查询今日运营数据 - GET接口)

(1)需求分析

(2)代码开发

[2、查询今日运营数据 - GET接口](#2、查询今日运营数据 - GET接口)

(1)需求分析

(2)代码开发

[3、查询菜品总览 - GET接口](#3、查询菜品总览 - GET接口)

(1)需求分析

(2)代码开发

[4、查询套餐总览 - GET接口](#4、查询套餐总览 - GET接口)

(1)需求分析

(2)代码开发

二、Excel表格导出

[1、Apache POI](#1、Apache POI)

(1)入门案例

2、导出Excel表格模块

(1)需求分析

(2)代码开发

【1】导入excel模板文件

【2】controller层

【3】service层


一、工作台模块

1、查询今日运营数据 - GET接口

(1)需求分析

(2)代码开发

【1】controller层

java 复制代码
    /**
     * 工作台今日数据查询
     * @return
     */
    @GetMapping("/businessData")
    @ApiOperation("工作台今日数据查询")
    public Result<BusinessDataVO> businessData(){
        //获得当天的开始时间
        LocalDateTime begin = LocalDateTime.now().with(LocalTime.MIN);
        //获得当天的结束时间
        LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        return Result.success(businessDataVO);
    }

【2】service层

  • 这里接口都可以复用之前开发过的
  • 我们需要返回的数据有:
    • 订单完成率 = 有效订单数 ÷ 订单总数
    • 平均客单价 = 营业额 ÷ 有效订单数
    • 营业额
    • 有效订单数
    • 新增用户数
  • 那我们需要的数据就是【订单总数】【有效订单数】【营业额】【新增用户数】,这些都是之前统计模块开发的mapper接口,直接复用即可
java 复制代码
    /**
     * 根据时间段统计营业数据
     * @param begin
     * @param end
     * @return
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额:当日已完成订单的总金额
         * 有效订单:当日已完成订单的数量
         * 订单完成率:有效订单数 / 总订单数
         * 平均客单价:营业额 / 有效订单数
         * 新增用户:当日新增用户的数量
         */

        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);

        //查询总订单数
        Integer totalOrderCount = orderMapper.countByMap(map);

        map.put("status", Orders.COMPLETED);
        //营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null? 0.0 : turnover;

        //有效订单数
        Integer validOrderCount = orderMapper.countByMap(map);

        Double unitPrice = 0.0;

        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0 && validOrderCount != 0){
            //订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
            //平均客单价
            unitPrice = turnover / validOrderCount;
        }

        //新增用户数
        Integer newUsers = userMapper.countByMap(map);

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

2、查询今日运营数据 - GET接口

(1)需求分析

(2)代码开发

【1】controller层

java 复制代码
    /**
     * 查询订单管理数据
     * @return
     */
    @GetMapping("/overviewOrders")
    @ApiOperation("查询订单管理数据")
    public Result<OrderOverViewVO> orderOverView(){
        
        return Result.success(workspaceService.getOrderOverView());
    }

【2】service层

java 复制代码
    /**
     * 查询订单管理数据
     *
     * @return
     */
    public OrderOverViewVO getOrderOverView() {
        Map map = new HashMap();
        map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
        map.put("status", Orders.TO_BE_CONFIRMED);

        //待接单
        Integer waitingOrders = orderMapper.countByMap(map);

        //待派送
        map.put("status", Orders.CONFIRMED);
        Integer deliveredOrders = orderMapper.countByMap(map);

        //已完成
        map.put("status", Orders.COMPLETED);
        Integer completedOrders = orderMapper.countByMap(map);

        //已取消
        map.put("status", Orders.CANCELLED);
        Integer cancelledOrders = orderMapper.countByMap(map);

        //全部订单
        map.put("status", null);
        Integer allOrders = orderMapper.countByMap(map);

        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

3、查询菜品总览 - GET接口

(1)需求分析

(2)代码开发

【1】controller层

java 复制代码
    /**
     * 查询菜品总览
     * @return
     */
    @GetMapping("/overviewDishes")
    @ApiOperation("查询菜品总览")
    public Result<DishOverViewVO> dishOverView(){
        
        return Result.success(workspaceService.getDishOverView());
    }

【2】service层

java 复制代码
    /**
     * 查询菜品总览
     *
     * @return
     */
    public DishOverViewVO getDishOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = dishMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = dishMapper.countByMap(map);

        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

【3】mapper层

java 复制代码
    /**
     * 根据条件统计菜品数量
     * @param map
     * @return
     */
    Integer countByMap(Map map);

【4】mybatis文件

XML 复制代码
    <select id="countByMap" resultType="java.lang.Integer">
        select count(id) from sky_take_out.dish
        <where>
            <if test="status != null">and status = #{status}</if>
            <if test="categoryId != null">and category_id = #{categoryId}</if>
        </where>
    </select>

4、查询套餐总览 - GET接口

(1)需求分析

(2)代码开发

【1】controller层

java 复制代码
    /**
     * 查询套餐总览
     * @return
     */
    @GetMapping("/overviewSetmeals")
    @ApiOperation("查询套餐总览")
    public Result<SetmealOverViewVO> setmealOverView(){
        return Result.success(workspaceService.getSetmealOverView());
    }

【2】service层

java 复制代码
    /**
     * 查询套餐总览
     *
     * @return
     */
    public SetmealOverViewVO getSetmealOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = setmealMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = setmealMapper.countByMap(map);

        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

【3】mapper层

java 复制代码
    /**
     * 根据条件统计套餐数量
     * @param map
     * @return
     */
    Integer countByMap(Map map);

【4】mybatis文件

XML 复制代码
    <select id="countByMap" resultType="java.lang.Integer">
        select count(id) from sky_take_out.setmeal
        <where>
            <if test="status != null">and status = #{status}</if>
            <if test="categoryId != null">and category_id = #{categoryId}</if>
        </where>
    </select>

工作台模块开发完毕!

二、Excel表格导出

1、Apache POI

Apache POI 是一个开源的Java库,用于读写Microsoft Office格式文件,它提供了API来操作Excel、Word、PowerPoint等文件。

(1)入门案例

【1】导入maven

XML 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </dependency>

【2】创建测试代码

java 复制代码
/**
 * 使用POI操作Excel文件
 */
public class POITest {

    /**
     * 通过POI创建Excel文件并且写入文件内容
     */
    public static void write() throws Exception{
        //在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();
        //在Excel文件中创建一个Sheet页
        XSSFSheet sheet = excel.createSheet("info");
        //在Sheet中创建行对象,rownum编号从0开始
        XSSFRow row = sheet.createRow(1);
        //创建单元格并且写入文件内容
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("城市");

        //创建一个新行
        row = sheet.createRow(2);
        row.createCell(1).setCellValue("张三");
        row.createCell(2).setCellValue("北京");

        row = sheet.createRow(3);
        row.createCell(1).setCellValue("李四");
        row.createCell(2).setCellValue("南京");

        //通过输出流将内存中的Excel文件写入到磁盘
        FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"));
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();
    }


    /**
     * 通过POI读取Excel文件中的内容
     * @throws Exception
     */
    public static void read() throws Exception{
        InputStream in = new FileInputStream(new File("D:\\info.xlsx"));

        //读取磁盘上已经存在的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //读取Excel文件中的第一个Sheet页
        XSSFSheet sheet = excel.getSheetAt(0);

        //获取Sheet中最后一行的行号
        int lastRowNum = sheet.getLastRowNum();

        for (int i = 1; i <= lastRowNum ; i++) {
            //获得某一行
            XSSFRow row = sheet.getRow(i);
            //获得单元格对象
            String cellValue1 = row.getCell(1).getStringCellValue();
            String cellValue2 = row.getCell(2).getStringCellValue();
            System.out.println(cellValue1 + " " + cellValue2);
        }

        //关闭资源
        in.close();
        excel.close();
    }

    public static void main(String[] args) throws Exception {
        //write();
        read();
    }
}

2、导出Excel表格模块

(1)需求分析

(2)代码开发

实现步骤:

  • 设计 Excel 模板文件
  • 查询近30天的运营数据
  • 将查询到的运营数据写入模板文件
  • 通过输出流将 Excel 文件下载到客户端浏览器
【1】导入excel模板文件

资料包day12中获取运营数据报表模板并导入

【2】controller层

HttpServletResponse response作用:

提供一个输出通道,让服务器能够将生成的Excel文件直接流式传输到客户端浏览器,实现文件下载功能

java 复制代码
    /**
     * 导出运营数据报表
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("导出运营数据报表")
    //HttpServletResponse response作用
    //提供一个输出通道,让服务器能够将生成的Excel文件直接流式传输到客户端浏览器,实现文件下载功能
    public void export(HttpServletResponse response){
        reportService.exportBusinessData(response);
    }
【3】service层
  • 查询数据库获取营业数据
  • 通过POI将数据写入excel表
    • 基于模板文件创建新excel文件
    • 填充时间
    • 填充概览数据
    • 填充详细数据
  • 通过输出流将excel下载到客户端浏览器
java 复制代码
    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库获取营业数据
        //概览数据包括:营业额、订单完成率、新增用户数、有效订单、平均客单价
        //上述数据刚好在工作台模块统计过,所以直接调用WorkspaceService即可
        LocalDate dateBegin = LocalDate.now().minusDays(30); //30天前的日期
        LocalDate dateEnd = LocalDate.now().minusDays(1);//昨天的日期

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2.通过POI将数据写入到Excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        /**
         * this.getClass() - 获取当前类的Class对象
         * .getClassLoader() - 获取类加载器
         * .getResourceAsStream("template/运营数据报表模板.xlsx") - 从类路径加载指定文件为输入流
         */

        try {
            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //(1)填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+dateBegin+"至"+dateEnd);

            //(2)填充营业概览数据
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //(3)填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3.通过输出流将Excel下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

导出excel文件成功!

相关推荐
kobe_OKOK_4 小时前
Django ORM 字段查询表达式(Field lookup expressions)
后端·python·django
qq_5470261794 小时前
SpringBoot+Redis实现电商秒杀方案
spring boot·redis·后端
程序猿DD5 小时前
如何在 Spring Boot 应用中配置多个 Spring AI 的 LLM 客户端
spring boot·llm·spring ai
Code blocks5 小时前
SpringBoot自定义请求前缀
java·spring boot·后端
爱学大树锯5 小时前
【Spring Boot JAR 解压修改配置后重新打包全流程(避坑指南)】
spring boot·后端·jar
kobe_OKOK_5 小时前
Django ORM 无法通过 `ForeignKey` 自动关联,而是需要 **根据父模型中的某个字段(比如 ID)去查询子模型**。
后端·python·django
Jabes.yang5 小时前
Java求职面试:从Spring Boot到Kafka的技术探讨
java·spring boot·面试·kafka·互联网大厂
程序员爱钓鱼6 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go
canonical_entropy6 小时前
DDD本质论:从哲学到数学,再到工程实践的完整指南之实践篇
java·后端·领域驱动设计