EasyPOI导出报表(一)-常规报表导出

报表导出是一种很常见的功能,只要是开发都会涉及到这一功能,早些年经常集成poi完成导出功能,我之前也有写过关于poi导出的文章,现如今,也有了更为方便的导出插件 — EasyPOI,废话不多说,开始撸代码

第一步:pom.xml添加EasyPOI依赖

 <!-- easypoi相关-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.2.0</version>
        </dependency>

第二步:编写easypoi导出工具类

package com.example.work.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: 导入导出工具类
 * @Author: lyz
 * @CreateTime: 2023-12-28
 */
public class EasyPoiUtils {


    /**
     * @Description:  excel-常规导出
     * @param[1] list 数据列表
     * @param[2] title 报表标题
     * @param[3] sheetName excel工作表名
     * @param[4] pojoClass 导出实体类
     * @param[5] fileName 导出excel文件名称
     * @param[6] response
     **/
    public static void export(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                              HttpServletResponse response)
            throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        //表格列数
        int physicalNumberOfCells = workbook.getSheetAt(0).getRow(0).getPhysicalNumberOfCells();
        //表格行数
        int lastRowNum = workbook.getSheetAt(0).getLastRowNum();
        //设置表头样式
        setTitleCellStyle(workbook, physicalNumberOfCells);
        //设置表格内容样式
        setContentCellStyle(workbook,physicalNumberOfCells,lastRowNum);
        //下载excel文件
        downLoadExcel(workbook,fileName, response);
    }

    private static void setContentCellStyle(Workbook workbook,int physicalNumberOfCells,int lastRow) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平对齐居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐在单元格的高度上居中
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //设置单元格格式
        for (int i = 1; i <= lastRow; i++) {
            Row rows = workbook.getSheetAt(0).getRow(i);
            for (int j = 0; j < physicalNumberOfCells; j++) {
                rows.getCell(j).setCellStyle(cellStyle);
            }
        }
    }

    private static void setTitleCellStyle(Workbook workbook,int physicalNumberOfCells) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平对齐居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐在单元格的高度上居中
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //设置字体样式
        Font font = workbook.createFont();
        font.setBold(true);
        cellStyle.setFont(font);
        // 设置背景颜色
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW1.getIndex());
        // 设置填充样式
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Row row = workbook.getSheetAt(0).getRow(0);
        for (int j = 0; j < physicalNumberOfCells; j++) {
            row.getCell(j).setCellStyle(cellStyle);
        }
    }


    /**
     * excel下载
     * @param[1] workbook 工作簿对象
     * @param[2] fileName 下载时的文件名称
     * @param[3] response
     */
    private static void downLoadExcel(Workbook workbook, String fileName, HttpServletResponse response)
            throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx",
                    "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

}

第三步:编写导出方法(只粘贴主要部分代码)

实体类

package com.example.work.entity;

import java.math.BigDecimal;
import java.util.Date;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

@Data
public class Employee {
    /**
    * id
    */
    private Integer id;

    /**
    * 姓名
    */
    @Excel(name = "姓名")
    private String name;

    /**
    * 性别 1-男;2-女
    */
    @Excel(name = "性别",replace = {"男_1", "女_2"})
    private Byte sex;

    /**
    * 出生地
    */
    @Excel(name = "出生地")
    private String address;

    /**
     * 出生年月
     */
    @Excel(name = "出生年月",exportFormat = "yyyy-MM-dd",width = 15)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date birthDay;

    /**
    * 联系电话
    */
    @Excel(name = "联系电话",width = 15)
    private String phone;

    /**
    * 工资
    */
    @Excel(name = "工资(单位:元)",width = 15)
    private BigDecimal salary;
}

controller层

package com.example.work.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.example.work.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description: TODO
 * @Author: lyz
 * @CreateTime: 2024-01-10
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;


    @GetMapping("/export")
    public void export(HttpServletResponse response){
        employeeService.export(response);
    }
}

业务层

package com.example.work.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.work.dao.EmployeeMapper;
import com.example.work.entity.Employee;
import com.example.work.service.EmployeeService;
import com.example.work.util.EasyPoiUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: TODO
 * @Author: lyz
 * @CreateTime: 2024-01-10
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public void export(HttpServletResponse response) {
        try {
            List<Employee> list = this.list();
            String fileName = "员工工资报表";
            EasyPoiUtils.export(list,null,fileName,Employee.class,fileName,response);
        }catch (Exception e){
            throw new RuntimeException("导出失败");
        }

    }
}

数据库表数据:
在这里插入图片描述
第四步:启动程序,并调用导出接口,最后得到的效果如下
在这里插入图片描述

easypoi导出 这里用了@Excel注解,可根据实际需要选择要导出的字段,它也有很多属性可应对不同的需求,具体用法可自行百度,这里不做具体详述;导出的方法也做了封装,极大的简化了代码开发,对一般的导出需求能快速应用

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用 EasyPoi 导出一对多数据时,需要使用 `@ExcelCollection` 注解来标识一对多的关系。下面是一个示例: 假设我们有两个实体类: `Order` 和 `OrderItem`,一个订单可以对应多个订单项。 ```java public class Order { @Excel(name = "订单编号", orderNum = "0") private String orderId; @Excel(name = "订单总价", orderNum = "1") private BigDecimal totalPrice; @ExcelCollection(name = "订单项", orderNum = "2") private List<OrderItem> orderItemList; // 省略 getter 和 setter 方法 } public class OrderItem { @Excel(name = "订单项编号", orderNum = "0") private String orderItemId; @Excel(name = "商品名称", orderNum = "1") private String productName; @Excel(name = "商品数量", orderNum = "2") private Integer productQuantity; // 省略 getter 和 setter 方法 } ``` 在 `Order` 类中,我们使用 `@ExcelCollection` 注解标识 `orderItemList` 属性,表示一个订单有多个订单项。在导出时,EasyPoi 会自动处理一对多的数据,并将订单项列表展开成多行数据。 下面是一个导出示例: ```java // 构造数据 List<Order> orderList = new ArrayList<>(); Order order1 = new Order(); order1.setOrderId("1001"); order1.setTotalPrice(new BigDecimal(100)); List<OrderItem> orderItemList1 = new ArrayList<>(); OrderItem item1 = new OrderItem(); item1.setOrderItemId("101"); item1.setProductName("商品1"); item1.setProductQuantity(2); orderItemList1.add(item1); OrderItem item2 = new OrderItem(); item2.setOrderItemId("102"); item2.setProductName("商品2"); item2.setProductQuantity(3); orderItemList1.add(item2); order1.setOrderItemList(orderItemList1); orderList.add(order1); // 导出 ExcelExportUtil.exportExcel(new ExportParams("订单列表", "订单"), Order.class, orderList, new FileOutputStream("order.xls")); ``` 在导出结果中,我们可以看到订单项被展开成了多行数据: | 订单编号 | 订单总价 | 订单项编号 | 商品名称 | 商品数量 | | :-----: | :-----: | :-----: | :-----: | :-----: | | 1001 | 100 | 101 | 商品1 | 2 | | | | 102 | 商品2 | 3 |

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值