使用EasyPoi导出Excel

这篇具有很好参考价值的文章主要介绍了使用EasyPoi导出Excel。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、引入Java包依赖

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.2.0</version>
</dependency>

2、创建导出的Excel样式类:

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;

import cn.afterturn.easypoi.excel.export.styler.AbstractExcelExportStyler;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
/**
 * @ClassName: ExcelExportMyStylerImpl
 * @Description: 自定义报表导出样式,可以修改表头颜色,高度等
 * @Author: sunt
 * @Date: 2019/8/29 21:39
 * @Version 1.0
 **/
public class ExcelExportMyStylerImpl extends AbstractExcelExportStyler implements IExcelExportStyler {

    public ExcelExportMyStylerImpl(Workbook workbook) {
        super.createStyles(workbook);
    }

    @Override
    public CellStyle getTitleStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);// 加粗
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        titleStyle.setFillForegroundColor(IndexedColors.AQUA.index);// 设置颜色
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setWrapText(true);
        return titleStyle;
    }

    @SuppressWarnings("deprecation")
    @Override
    public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }

    @Override
    public CellStyle getHeaderStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);// 加粗
        font.setColor(IndexedColors.RED.index);
        font.setFontHeightInPoints((short) 11);
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 居中
        titleStyle.setFillForegroundColor(IndexedColors.WHITE.index);// 设置颜色
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setWrapText(true);
        return titleStyle;
    }

    @SuppressWarnings("deprecation")
    @Override
    public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }
}

 

3、创建核心导出工具类

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sunny.spring.boot.poi.common.ExcelExportMyStylerImpl;
import com.sunny.spring.boot.poi.pojo.StudentInfoBean;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: ExcelExportUtil
 * @Description: Exceld导出工具类
 * @Author: sunt
 * @Date: 2019/8/30 14:49
 * @Version 1.0
 **/
public class MyExcelExportUtil {

    /**
     * Excel文件导出,导出的文件名默认为:headTitle+当前系统时间
     * @param listData 要导出的list数据
     * @param pojoClass 定义excel属性信息
     * @param headTitle Excel文件头信息
     * @param sheetName Excel文件sheet名称
     * @param response
     */
    public static void exportExcel(Collection<?> listData,Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response) {
        ExportParams params = new ExportParams(headTitle, sheetName);
        params.setHeight((short) 8);
        params.setStyle(ExcelExportMyStylerImpl.class);
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
            String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setContentType("application/vnd.ms-excel;chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName + ".xls");
            ServletOutputStream out=response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

4、创建导出对象实体Bean

注意日期类型 注解内要加上: exportFormat = "yyyy-MM-dd hh:mm:ss"

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * <p>
 * 学生基本信息表
 * </p>
 *
 * @author sunt
 * @since 2019-08-29
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("T_STUDENT")
public class StudentInfoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 学号
     */
    @TableId("ID")
    @Excel(name = "学号", width = 20, orderNum = "1")
    private String id;

    /**
     * 姓名
     */
    @TableField("NAME")
    @Excel(name = "姓名", width = 20, orderNum = "2")
    private String name;

    /**
     * 性别(1:男 2:女)
     * replace:导出是{a_id,b_id} 导入反过来,注意大括号里面单独引号引起来的
     */
    @TableField("SEX")
    @Excel(name = "性别", width = 20, replace = { "男_1", "女_2" },orderNum = "3")
    private String sex;

    /**
     * 年龄
     */
    @TableField("AGE")
    @Excel(name = "年龄", width = 20, orderNum = "4")
    private Integer age;

    /**
     * 出生日期
     */
    @TableField("BIRTHDAY")
	@Excel(name = "商品创建时间", width = 20, orderNum = "12",exportFormat = "yyyy-MM-dd hh:mm:ss")
    private String birthday;

    /**
     * 入学时间
     */
    @TableField("REGIST_DATE")
    @Excel(name = "入学时间",width = 20,orderNum = "6")
    private String registDate;

    /**
     * 学费
     */
    @TableField("FEE")
    @Excel(name = "学费", width = 20, orderNum = "7")
    private BigDecimal fee;


}

 

属性字段 属性值
@TableField 这个字段代表数据库表的字段
@Excel name代表导出Excel列名称
@Excel orderNum代表Excel列排在第几列
@Excel replace一般数据库存的性别例如0和1,导出的值0展示为男性,女展示为女性

 

5、后台方法:

直接调用查询方法,返回给前台就OK

   @RequestMapping("/exportStudent")
    public void exportStudent(HttpServletResponse response) {
        try {
            List<StudentInfoBean> sutdentList = studentService.queryAllStudent();
            MyExcelExportUtil.exportExcel(sutdentList,StudentInfoBean.class,"学生基本信息","新生入学信息",response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

6、前台的方法

不能使用ajax方法,返回的是字符串,后台返回的是流,如果用ajax返回的是乱码,并且浏览器不下载文章来源地址https://www.toymoban.com/news/detail-413966.html

   //导出excel
    excel(){
      window.open("http://localhost:88/api/shop/shop/exportShop")
    },

到了这里,关于使用EasyPoi导出Excel的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 模板文件导出Excel【EasyPoi实战系列】- 第478篇

    ​历史文章( 文章 累计470+) 《国内最全的Spring Boot系列之一》 《国内最全的Spring Boot系列之二》 《国内最全的Spring Boot系列之三》 《国内最全的Spring Boot系列之四》 《国内最全的Spring Boot系列之五》 《国内最全的Spring Boot系列之六》 【EasyPoi实战系列】Spring Boot使用Ea

    2024年02月11日
    浏览(23)
  • 【业务功能篇47】Springboot+EasyPoi 实现Excel 带图片列的导入导出

    SpringBoot整合EasyPoi实现Excel的导入和导出(带图片)_51CTO博客_springboot easypoi导出excel

    2024年02月16日
    浏览(34)
  • 使用若依框架和 EasyPoi 导出 Word 文档的方法详解

    若依框架是一个基于 Spring Boot 和 Vue 的快速开发平台,而 EasyPoi 是一个方便的 Java 导入导出工具库。本文将介绍如何在若依框架中使用 EasyPoi 导出 Word 文档,帮助你实现简单且高效的导出功能。 首先,我们需要在若依框架中添加 EasyPoi 的依赖。可以通过 Maven 或 Gradle 来管理依

    2024年02月13日
    浏览(91)
  • 使用原生POI和EasyPoi根据word模板导出word工具类

    前两天接了个需求,要求将数据导出成word,里边有边个,有其他的东西,怎么说这,这个需求最开始就是上传word,下载附件就行了,非得改成上传数据然后支持下载word。有股脱裤子放屁的感觉 而且呢,当时做的时候前任开发在数据库存了一个巨大的Json文件,解析也挺费劲的

    2024年01月25日
    浏览(42)
  • 使用easypoi-spring-boot-starter 4.1.1导入excel报错NoSuchMethodError和NoSuchMethodError

    使用easypoi进行excel的导入遇到的错误以及解决办法 easypoi项目地址:https://gitee.com/lemur/easypoi easypoi的Maven依赖: 报错描述: 解决办法: XmlOptions.setEntityExpansionLimit() 错误,是 jar 包版本引起的,3.0 版本以下的 xmlbeans 中根本没有该方法,需要将jar升级到 3.0+ 版本才可以。另外

    2024年02月08日
    浏览(35)
  • easypoi 导出word表格

    template.docx 模板内容: {{0}} {{1}} {{2}} {{3}} {{4}} {{5}} 学生姓名 学生年龄 学生生日 语文成绩 数学成绩 template_job.docx 模板内容: 名称 年龄 地址 名称2 {{user.name}} {{user.age}} {{user.address}} {{user.other}} 公司名称 地址 {{$fe:jobs t.name t.address}}

    2024年02月13日
    浏览(77)
  • Easypoi word 模板导出问题

    按word模板导出报错 源代码:  报的错误信息: 错误原因:linux环境路径找不到 linux 环境打印路径如下: templateFile.getPath():file:/home/sjzx/backend/admin/sjzx-admin-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/word/template.docx windos环境打印路径ruxi templateFile.getPath():D:workplacesjzx-backendsjzx-admintargetclasse

    2024年02月01日
    浏览(28)
  • 【java】EasyPoi导出导入(合并单元格)

    2024年02月14日
    浏览(28)
  • easypoi 导出word并插入echart图片和文件

    插件包含内容: 1 phantomjs-2.1.1-windows 执行转化图片命令 2 echarts-convert js生成ecahrt 图片  

    2024年02月12日
    浏览(177)
  • spring boot 整合EasyPoi导入导出,下载模版功能

    name:Excel中的列名; width:指定列的宽度; needMerge:是否需要纵向合并单元格; format:当属性为时间类型时,设置时间的导出导出格式; desensitizationRule:数据脱敏处理,3_4表示只显示字符串的前3位和后4位,其他为*号; replace:对属性进行替换; suffix:对数据添加后缀。

    2024年02月11日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包