java-EasyExcel模板导出
前言:
需求:根据自定义模板导出Excel,包含图片、表格,采用EasyExcel
提示:EasyExcel请使用 3.0 以上版本,
对图片操作最重要的类就是 WriteCellData<Void> 如果你的easyexcel没有这个类,说明你的版本太低,请升级到3.0以上
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.1</version>
</dependency>
实际代码:
Controller
@ApiOperation("excel导出详情")
@PostMapping("excelExport")
public void excelExport(HttpServletResponse response,
@ApiParam("id {\"id\":\"xxx\"}") @RequestBody Map<String, String> data) {
ExcelUitl.templateExport(response, researcherInformationService
.getDetail(data.get("id")));
}
ServiceImpl
public static String templateExport(HttpServletResponse response,ResearchDetailVo researchDetailVo) {
InputStream is = null;
try {
// 取出模板
is = ResourceUtil.getStream("classpath:templates/survey.xlsx");
Map<String, Object> map = new HashMap<>(10);
map.put("goOutDate", researchDetailVo.getGoOutDate());
map.put("userName", researchDetailVo.getUserName());
map.put("visitPlace", researchDetailVo.getVisitPlace());
map.put("marketTrends", researchDetailVo.getMarketTrends());
map.put("marketEnvironment", researchDetailVo.getMarketEnvironment());
map.put("partnerTrends", researchDetailVo.getPartnerTrends());
map.put("companyStatus", researchDetailVo.getCompanyStatus());
map.put("marketCompetition", researchDetailVo.getMarketCompetition());
map.put("feedback", researchDetailVo.getFeedback());
// 文件名称
String fileName = researchDetailVo.getUserName() + researchDetailVo.getGoOutDate()
+ "调研反馈信息表";
if (!ObjectUtils.isEmpty(researchDetailVo.getUrl())) {
//图片url转换为MultipartFile对象
// getUrl 是 List<String>
MultipartFile[] files = downloadImages(researchDetailVo.getUrl());
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
// 图像设置处理
WriteCellData<Void> voidWriteCellData = imageCells(file.getBytes());
map.put("img" + (i + 1), voidWriteCellData);
}
}
ExcelWriter excelWriter = EasyExcel.write(getOutputStream(fileName, response)).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(map, writeSheet);
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static WriteCellData<Void> imageCells(byte[] bytes) throws IOException {
WriteCellData<Void> writeCellData = new WriteCellData<>();
// 可以放入多个图片
List<ImageData> imageDataList = new ArrayList<>();
writeCellData.setImageDataList(imageDataList);
ImageData imageData = new ImageData();
imageDataList.add(imageData);
// 设置图片
imageData.setImage(bytes);
// 图片类型
//imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG);
// 上 右 下 左 需要留空,这个类似于 css 的 margin;
// 这里实测 不能设置太大 超过单元格原始大小后 打开会提示修复。暂时未找到很好的解法。
imageData.setTop(10);
imageData.setRight(10);
imageData.setBottom(10);
imageData.setLeft(10);
// * 设置图片的位置。Relative表示相对于当前的单元格index。first是左上点,last是对角线的右下点,这样确定一个图片的位置和大小。
// 目前填充模板的图片变量是images,index:row=CELL_COUNT,column=0。所有图片都基于此位置来设置相对位置
// 第1张图片相对位置
imageData.setRelativeFirstRowIndex(0);
imageData.setRelativeFirstColumnIndex(0);
imageData.setRelativeLastRowIndex(0);
imageData.setRelativeLastColumnIndex(0);
return writeCellData;
}
///为什么用线程池去实现 原因:当时项目文件储存用的是minio,由于服务器宽带非常低,导致几百K的图片都需要很久,多图片需要加载资源很久
public static MultipartFile[] downloadImages(List<String> imageUrls) {
// 创建一个固定大小的线程池
int poolSize = 5;
ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, poolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
MultipartFile[] files = new MultipartFile[imageUrls.size()];
for (int i = 0; i < imageUrls.size(); i++) {
final int index = i;
executor.submit(() -> {
try {
files[index] = convert(imageUrls.get(index));
} catch (IOException e) {
e.printStackTrace();
}
});
}
executor.shutdown(); // 关闭线程池
// 等待所有任务执行完成
while (!executor.isTerminated()) {
// 等待
}
return files;
}
/**
* 图片地址转换为MultipartFile文件
*
* @param imageUrl
* @return
* @throws IOException
*/
public static MultipartFile convert(String imageUrl) throws IOException {
// 将在线图片地址转换为URL对象
URL url = new URL(imageUrl);
// 打开URL连接 转换为HttpURLConnection对象
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
// 获取输入流 并读取输入流中的数据,并保存到字节数组中
InputStream inputStream = httpURLConnection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
return new MockMultipartFile("file", "filename.jpg", "image/jpeg", byteArrayInputStream);
}
xlsx模板位置

xlsx模板内容

导出内容展示

java-EasyExcel模板导出的更多相关文章
- java根据模板导出PDF详细教程
原文:https://blog.csdn.net/pengyufight/article/details/75305128 题记:由于业务的需要,需要根据模板定制pdf文档,经测试根据模板导出word ...
- Java按模板导出Excel———基于Aspose实现
目录 开发环境 先看效果 引入jar包 校验许可证 导出方法 测试结果 占位符 开发环境 jdk 1.8 Maven 3.6 SpringBoot 2.1.4.RELEASE aspose-cells ...
- Java无模板导出Excel,Apache-POI插件实现
开发环境 jdk 1.8 Maven 3.6 Tomcat 8.5 SpringBoot 2.1.4.RELEASE Apache-POI 3.6 Idea 注意: 我是在现有的基于SpringBoo ...
- java根据模板导出PDF(利用itext)
一.制作模板 1.下载Adobe Acrobat 9 Pro软件(pdf编辑器),制作模板必须使用该工具. 2.下载itextpdf-5.5.5.jar.itext-asian-5.2.0.j ...
- 关于Java中excel表格导出的总结(Java程序导出模板和Java根据模板导出表格两种实现方式)
导出excel通用模板(程序定义模板导出) 转载原文:https://www.jianshu.com/p/5c7b359a159c 如下代码,本方法主要用于程序定义模板格式,并导出文件.该方法将定义和 ...
- Java 根据模板导出PDF
目录 前言 思路一:直接导出pdf 使用itext模板导出pdf 思路二:先导出word再转成pdf 1)导出word 2)word转pdf 最终方案 docx4j spire.doc.free + ...
- java根据模板导出pdf
在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模板,有的只是随便把数据放里面生成文件,完全不考虑数据怎样放置的以及以后的维护性,想想还是自己总结一个完全版的导出 ...
- java五行代码导出Excel
目录 先看代码 再看效果 EasyExcel 附: Java按模板导出Excel---基于Aspose实现 Java无模板导出Excel,Apache-POI插件实现 已经写过两种Excel导出插件了 ...
- java使用jxls导出Excel
jxls是基于POI的Excel模板导出导入框架.通过使用类似于jstl的标签,有效较少导出Excel的代码量. 1.pom <!-- https://mvnrepository.com/art ...
- java实现excel模板导出
一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...
随机推荐
- UI获取元素的几种方式
通过浏览器驱动获取页面元素的8种方式. 定位方法: 通过webdriver对象的find_element方法 通过 id获取元素 el = driver.find_element(By.ID,'id' ...
- 想了解API接口,这一篇就够了
API(Application Programming Interface)接口,对于大多数人来说可能还比较陌生,但实际上我们每天都在与它打交道.无论是使用手机上的应用程序,还是在网上购物,都少不了A ...
- 【题解】AtCoder Beginner Contest 318(D - Ex)
赛时过了 A-G,Ex 仿佛猜到了结论但是完全不懂多项式科技,就炸了. 大家好像都秒了 A,B,C 就不写了. D.General Weighted Max Matching 题目描述: 给你一个加权 ...
- signalr断开连接后重新连接
signalr断开连接后重新连接 产品需求连接signalr 不稳定,连着连着就断了,场面十分尴尬,导致产品经理现场被批!!(内心无比高兴 ) 分析得出问题现象: 服务器因某些特殊原因,导致服务停止一 ...
- Docker 镜像库国内加速的几种方法
概述 在国内,拉取 Docker 镜像速度慢/时不时断线/无账号导致限流等,比较痛苦. 这里提供加速/优化的几种方法. 梳理一下,会碰到以下情况: 国内下载速度慢/时不时断线:是因为网络被限制了. 没 ...
- 使用极速全景图下载大师下载720yun全景图片(一键下载建E、720云全景原图)
VR全景图片下载 软件简介 极速全景图下载大师下载地址: 点击进入下载页面 极速全景图下载大师(VR全景图下载器)软件官网: 点击进入官网 极速全景图下载大师如何下载720yun全景图片 1.首先,在 ...
- 面试官:说一下 MyBatis 缓存机制?
MyBatis 的缓存机制属于本地缓存,适用于单机系统,它的作用是减少数据库的查询次数,提高系统性能. MyBaits 中包含两级本地缓存: 一级缓存:SqlSession 级别的,是 MyBatis ...
- Solution -「ZJOI 2014」力
Descrption Link. 对于每一个 \(i\),求出: \[\sum_{j=1}^{i-1}\frac{a_{j}}{(i-j)^{2}}-\sum_{j=i+1}^{n}\frac{a_{ ...
- Hadoop - WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform...
Hadoop - WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... 配置完ha ...
- cmake构建32位应用程序
1. 背景介绍 2. 工具介绍 3. 环境搭建 4. MinGW编译器版本 1. 背景介绍 最近需要使用第三方动态库文件G33DDCAPI.dll进行二次开发.由于这个动态库文件生成的时间比较早,且只 ...