EasyPoi通过模板生成Excel文件

Easypoiexcel模板导出 模板导出跟简单导出多,只是controller层略微有点差别,另外要准备一个导出模板 其他代码点击Easypoiexcel简单导入 controller层代码 /** * 多sheet导入Excel数据 */ @RequestMapping(value = "multImports",method = RequestMethod.POST) @ResponseBody public String multImports(MultipartFile fil 阅读详情

之前用easypoi实现过导出简单的excel文件,最近又有需求导出固定格式的excel文件,所以在网上搜索学习了一下,现将学会后写的demo记录一下方便以后回顾。

  首先照例引入maven依赖(这里版本要注意一下,之前引入4.3.0导出图片会失败,后面在网上看到有人遇到同样的问题,换成4.2.0后就可以正常导出图片了):

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

然后在resources路径下创建一个用来存放模板的文件夹:template

 接着在配置文件application.yml里写上该模板文件的路径,方便代码引用:

template:
  city-rail-report: template/city_rail_report_template.xlsx

然后创建一个导出excel的工具类:

package com.wl.standard.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author wl
 * @date 2022/1/7
 */
@Slf4j
public class ExcelUtils {
    /**
     * 通过模板生成Excel文件
     * @param templateFileName 模板文件
     * @param fileName 目标文件
     * @param map 数据
     */
    public static void buildExcelByTemplate(String templateFileName, String fileName, Map map) {
        OutputStream outStream = null;
        try {
            outStream = new FileOutputStream(fileName);
            TemplateExportParams param = new TemplateExportParams(templateFileName, 0);
            Workbook workbook = ExcelExportUtil.exportExcel(param, map);
            workbook.write(outStream);
        } catch (IOException e) {
            log.error("根据模板生成Excel文件失败, 失败原因: {}", e);
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Controller层:

package com.wl.standard.controller;

import com.wl.standard.common.result.HttpResult;
import com.wl.standard.common.result.HttpResultWithPageInfo;
import com.wl.standard.entity.City;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.wl.standard.service.CityRailService;

/**
 * @author wl
 * @date 2021/7/14
 */
@Api(tags = "城市轨道交通信息")
@RestController
@RequestMapping("/rail")
public class CityRailController {
	private final CityRailService cityRailService;

	@Autowired
	public CityRailController(CityRailService cityRailService) {
		this.cityRailService = cityRailService;
	}


	@ApiOperation("生成Excel")
	@GetMapping("/build/report")
	public HttpResult buildReport() {
		cityRailService.buildReport();
		return HttpResult.success();
	}
}

Service实现层(本例引用了Mybatis-plus,仅做参考):

package com.wl.standard.service.impl;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wl.standard.common.PageInfoWrapper;
import com.wl.standard.entity.City;
import com.wl.standard.entity.CityRail;
import com.wl.standard.entity.vo.CityRailVO;
import com.wl.standard.utils.CommonUtils;
import com.wl.standard.utils.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import com.wl.standard.mapper.CityRailMapper;
import com.wl.standard.service.CityRailService;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wl
 * @date 2021/7/15
 */
@Slf4j
@Service
@EnableAsync
public class CityRailServiceImpl extends ServiceImpl<CityRailMapper, CityRail> implements CityRailService {
	@Value("${template.city-rail-report}")
	private String templateFile;

	@Override
	@Async
	public void buildReport() {
		Map<String, Object> data = new HashMap<>();
		List<CityRailVO> cityRailList = baseMapper.getCityRail();
		List<JSONObject> cityRailArray = new ArrayList<>();
		//插入图片
		cityRailList.forEach(cityRailVO -> {
			JSONObject cityRailObject = CommonUtils.toJsonObject(cityRailVO);
			if (StringUtils.isNotEmpty(cityRailVO.getImg())) {
				File imgFile = new File(cityRailVO.getImg());
				if (imgFile.exists()) {
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
					try {
						BufferedImage bufferImg = ImageIO.read(imgFile);
						ImageIO.write(bufferImg, "png", byteArrayOut);
						ImageEntity imageEntity = new ImageEntity(byteArrayOut.toByteArray(), 1000, 1000);
						cityRailObject.put("img", imageEntity);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			cityRailArray.add(cityRailObject);
		});
		data.put("cityRail", cityRailArray);
		data.put("mileage", statistics(cityRailList));
		String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
		String fileName = String.format("%s.xlsx", now);
		ExcelUtils.buildExcelByTemplate(templateFile, fileName, data);
	}

	/**
	 * 统计
	 * @param cityRailList
	 * @return
	 */
	private JSONObject statistics(List<CityRailVO> cityRailList) {
		JSONObject mileage = new JSONObject();
		Long top = cityRailList.stream().filter(cityRailVO -> cityRailVO.getMileage() > 500).count();
		Long middle = cityRailList.stream().filter(cityRailVO -> cityRailVO.getMileage() > 300 && cityRailVO.getMileage() < 500).count();
		Long generally = cityRailList.stream().filter(cityRailVO -> cityRailVO.getMileage() > 100 && cityRailVO.getMileage() < 300).count();
		mileage.put("top", top);
		mileage.put("middle", middle);
		mileage.put("generally", generally);
		return mileage;
	}
}

模板文件内容:

对于list,需要采用{{ $fe: list t.xxx}}的格式,其中list是你的list对象名,如我的模板里list的对象名为cityRail。而t.xxx,xxx则是属性名称。

对于一般的对象,即可采用第2行的格式。

另外本demo采用了异步的方式,不用等文件生成成功就可以返回响应了,具体可以去了解@Async@EnableAsync注解。

启动项目,调用接口,生成文件:

 

Easypoi 导出Excel模板版) 1.添加POM文件依赖: <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.0.0</version> </depende... 阅读详情

相关推荐

开发笔记 | EasyPoi快速学习实现excel导入导出

easypoi学习笔记

qq_37630282的博客 8651

使用easypoi模板方法导出excel

使用excelpoi模板方法导出excel,实现横向与纵向输出数据

weixin_49832841的博客 1万+

JAVA实现Easypoi模版导出

在两个大括号里写对应的数据名称,单个元素数据(默认t,需要写),fe用来遍历数据,fe的写法 fe标志 : list数据 {{$fe:maplist t.id }}下面列举下EasyPoi支持的指令以及作用,workbook 对列数据进行处理。

m0_46300599的博客 4153

java easypoi导出Excel模板/Excel数据

2.导出数据文件Excel

weixin_47010136的博客 1556

使用easypoi模板多线程导出excel文件生成压缩文件下载,支持动态列

使用easypoi模板多线程导出excel文件生成压缩文件下载,支持动态列,注解方式、模板方式

Jnsone的博客 2136

EasyPoi 模板导出Excel (带图片) 以及一些踩坑记录

最近都是在写导出,那么为什么要用 easypoi呢,我用freemarker模板导出写好后,发现图片行,word转Base64编码就行,excel行,只能换一种了,一个导出弄一天。做个记录,你知道的越多,知道的越多。 EasyPoi官网 展示效果(正面 sheet) (反面 sheet) 1. EasyPoi模板导出 1.1 准备模板 用{{}}包裹变量就行,注意一点,图片所在的单元格用提前合并。 这边有个遍历填充的 第一个单元格:{{$fe: maplist t.familyName

庭前云落的博客 8916

springBoot整合easyPoi填充Excel模板

模板是处理复杂Excel的简单方法,复杂的Excel样式,可以用Excel直接编辑,完美的避开了代码编写样式的雷区,同时指令的支持,也提高了模板的有效性。 下面列举下EasyPoi支持的指令以及作用,最主要的就是各种fe的用法

qq_63815371的博客 5101

easypoi导出数值型_easypoi使用模板形式导出excel中sum的使用

在使用easypoi导出excel有涉及到sum的使用的,一般使用sum都是为了统计数值,并且是循环当中使用的。EasyPoi支持的指令以及作用空格分割三目运算 { {test ? obj:obj2}}n: 表示 这个cell是数值类型 { {n:}}le: 代表长度{ {le:()}} 在if/else 运用{ {le:() > 8 ? obj1 : obj2}}fd: 格式化时间 { {...

weixin_39959505的博客 1647

easypoi导出excel 效率_easypoi 快速开发 导出 各种姿势的excel

应用:基本可以应付所有变态的Excel导出需求,各种姿势!!Maven:cn.afterturneasypoi-base3.0.1cn.afterturneasypoi-annotation3.0.1cn.afterturneasypoi-web3.0.1模板导出:// 查询数据,此处省略List list = new ArrayList();int count1 = 0 ;EasyPOIMod...

weixin_39978444的博客 320

EasyPOI(三)将Excel打成压缩包批量导出

目录1. Service2. ServiceImpl 需求: 将模板生成Excel文件打成压缩包导出。 要求: 能在服务器生成冗余临时文件; 程序打成jar包执行时,可以准确找到Excel模板文件。 1. Service import org.springframework.http.ResponseEntity; /** * <p> @Title ExportService * <p> @Description 导出测试Service * * @au

ACGkaka的博客 1614

easypoi模板导出 多条数据_使用easyPoi根据提供的Excel模板导出数据

导出Excel文件要求的表头太复杂怎么办?easyPoi提供了一种可以使用模板导出数据的方法。这里是我自己抽取的一个工具类,用于单条数据导出。使用多条的数据导出详见官方API.package com.yonyou.aco.cpas.indp.util;import java.io.File;import java.io.FileOutputStream;import java.util.Map;i...

weixin_30540871的博客 1014

使用easypoi进行按模板导出excel格式

【代码】使用easyexcel进行按模板导出excel格式。

qq_41552885的博客 1199

EasyPoi

excel导入导出准备工作加入依赖数据类和模板类开干导出导入转化 准备工作 加入依赖 我用的是easypoi,非常好用,但需要注意一些坑。 <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.1</version&

weixin_45740898的博客 843

FreeMarker模板导出Word或Excel文件

一、前言 Java开发中,常见的导入/导出插件是EasyPoi,简单易学,功能强大。如果我们希望导出文件有复杂的样式的时,使用EasyPoi的POJO类处理显然就力从心,因此就得使用EasyPoi模板。由于项目部署环境和打包框架等问题,代码中获取EasyPoi模板比较困难且容易导致NPE。因此,可以使用FreeMarker模板来做替换,该方法生成文件时只需要传入文档流即可。 FreeMarker模板的制作,在本篇博客讨论。见本人另一篇博客: 二、导出功能实现 1. Controller..

大话家的博客 793

easypoi导出Excel报表(报表存入Aliyun OSS,返回前端路径)

使用easypoi导出满足各种需求的excel报表

weixin_65680938的博客 817

springboot easypoi 导入excel解析和导出替换word模板

springboot easypoi 导入excel解析和导出替换word模板

xiaogg3678的专栏 1704

poi 和 EasyPoi

poi 和 EasyPoi POI 什么是 POI Apache Poi 是 Apache 的一个开源项目,通过 poi 的 api 可以 实现Java代码 读取 和 生成 Excel 文档 为什么要学这个技术? 应用场景 Excel 导入,批量注册 教务管理系统,Excel文件中----》通过Poi读取到系统中 Excel 导出 批量导出,凭条打印,收据打印,统计信息导出(订单量 销售量)等 xls 07版以前 xlsx 07版以后 poi 支持两种格式 jxl只支持一种格式xls 文件读取导出只能是流

hacker_world的博客 1564

使用EasyPoi导入、导出excel

使用EasyPoi导入、导出excel

weixin_39527642的博客 6267
上一篇: SpringBoot搭配Quartz实现动态定时任务
下一篇: MySQL之INTERVAL()函数用法
wl_Honest
博客等级 码龄9年 64粉丝 · 66原创
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值