EasyPOI导出报表

发布时间:2024年01月10日

报表导出是一种很常见的功能,只要是开发都会涉及到这一功能,早些年经常集成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);
        //设置单元格格式
        setBorder(workbook);
        //下载excel文件
        downLoadExcel(workbook,fileName, response);
    }


    /**
     * 给指定行指定列设置边框
     * @param[1] workbook 工作簿对象
     */
    private static void setBorder(Workbook workbook) {
        Sheet sheet = workbook.getSheetAt(0);
        // 表格列数
        int physicalNumberOfCells = workbook.getSheetAt(0).getRow(0).getPhysicalNumberOfCells();
        //表格列数
        int lastRowNum = workbook.getSheetAt(0).getLastRowNum();

        for (int i = 0; i <= lastRowNum; i++) {
            for (int j = 0; j < physicalNumberOfCells; j++) {
                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);
                if (i == 0) {
                    // 设置背景颜色
                    cellStyle.setFillForegroundColor(IndexedColors.YELLOW1.getIndex());
                    // 设置填充样式
                    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    //设置字体样式
                    Font font = workbook.createFont();
                    font.setBold(true);
                    cellStyle.setFont(font);
                }

                Row row = sheet.getRow(i);
                Cell cell = row.getCell(j);
                cell.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注解,可根据实际需要选择要导出的字段,它也有很多属性可应对不同的需求,具体用法可自行百度,这里不做具体详述;导出的方法也做了封装,极大的简化了代码开发,对一般的导出需求能快速应用

文章来源:https://blog.csdn.net/qq_42570879/article/details/135513363
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。