当前位置:网站首页>Use POI to export excel file, image URL to export file, image and excel file to export compressed package
Use POI to export excel file, image URL to export file, image and excel file to export compressed package
2022-07-29 01:52:00 【Hard working ant [if you]】
I recently made a excel Export function , Fields involve pictures . But the demand is : Export a compressed package , The compressed package contains a excel Files and multiple pictures , Image naming is unique according to business .
preparation
Entity class
public class MessageDO {
private Integer id;
@ExcelExport(" cover ")
private String url;
@ExcelExport(" title ")
private String title;
@ExcelExport(" Content ")
private String content;
@ExcelExport(" Creation time ")
private LocalDateTime createTime;
@ExcelExport(" Update time ")
private LocalDateTime updateTime;
// Omit get、set Method
//..............
}
Test data
private List<MessageDO> getList() {
List<MessageDO> messageDOS = new ArrayList<>();
List<String> urlList = Arrays.asList("https://img-blog.csdnimg.cn/20210823171755669.png",
"https://img-blog.csdnimg.cn/20210705113753337.jpeg",
"https://img-blog.csdnimg.cn/20210823085631276.jpeg",
"https://img-blog.csdnimg.cn/20210823085620179.jpeg",
"https://img-blog.csdnimg.cn/2021082308560694.jpeg");
for (int i = 0; i < 5; i++) {
MessageDO messageDO = new MessageDO();
messageDO.setTitle(" This is the test title " + i);
messageDO.setContent(" This is the test content " + i);
messageDO.setUrl(urlList.get(i));
messageDO.setCreateTime(LocalDateTime.now());
messageDO.setUpdateTime(LocalDateTime.now());
messageDOS.add(messageDO);
}
return messageDOS;
}
Export what I use here is POI, I found one online to use POI Import and export articles , It's written very well .
Link to the original text :Java Realization Excel Import and export , Just read this one ( Collector's Edition )
This link provides many methods , If I want to use the export function , Directly use the one provided inside ExcelUtils Just tools .
maven rely on
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
<scope>compile</scope>
</dependency>
export excel
from the shallower to the deeper , The first is to realize the basic export function .
Control end code :
/** * Normal export * @param response */
@GetMapping("exportExcel")
public void exportExcel(HttpServletResponse response) {
List<MessageDO> messageDOS = getList();
ExcelUtils.export(response, " export ", messageDOS, MessageDO.class);
}
The effect is as follows :

This completes the ordinary excel export , Is it simple . It mainly uses the tool class of reference link .
Transfer the image address to the file download and package it into a compressed file
Generally, when we save pictures , Just save one url route .
My need is : according to url Download the pictures through the path , Put it in a compressed package .
Here I offer a FileUtil Tool class .
The process is divided into three steps :
- adopt url Link to download the file locally .
- Compress it into zip file .
- Delete the locally downloaded files .
The tool class code is as follows :
public class FileUtil{
/** * adopt url Download files to local * @param url network address * @return */
public static File getFileByUrl(String url) {
// Name local files
String fileName = url.substring(url.lastIndexOf("."));
File file = null;
URL urlfile;
InputStream inStream = null;
OutputStream os = null;
try {
file = File.createTempFile(System.currentTimeMillis() + "", fileName);
// download
urlfile = new URL(url);
inStream = urlfile.openStream();
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
if (null != inStream) {
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
/** * function : Compress multiple files , Output compressed zip File stream * @param zipFileName zip file name * @param files Exported files * @param imgNameList file name * @param response * @throws Exception */
public static void downZip(String zipFileName, List<File> files, List<String> imgNameList,
HttpServletResponse response) throws Exception {
byte[] buf = new byte[1024];
// Get the output stream
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
ZipOutputStream out = null;
try {
// An emphasis on
response.reset();
// Different types of files correspond to different MIME type
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + zipFileName + ".zip");
response.setContentType("application/octet-stream;charset=UTF-8");
//ZipOutputStream class : Complete the compression of files or folders
out = new ZipOutputStream(bos);
for (int i = 0; i < files.size(); i++) {
FileInputStream in = new FileInputStream(files.get(i));
// Name the files in the list separately
// To obtain the suffix
String imgUrl = files.get(i).getName();
String imgSuffix = imgUrl.substring(imgUrl.lastIndexOf("."));
out.putNextEntry(new ZipEntry(imgNameList.get(i) + imgSuffix));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.closeEntry();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(out)) {
out.flush();
out.close();
}
if (Objects.nonNull(bos)) {
bos.close();
}
// Delete file
delete(files);
}
}
/** * Local file delete * @param files Multiple files */
private static void delete(List<File> files) {
for (File file : files) {
file.delete();
}
}
}
Control end code :
/** * Through multiple pictures url Path download zip file * @param response * @throws Exception */
@GetMapping("exportImgZip")
public void exportImgZip(HttpServletResponse response) throws Exception {
List<MessageDO> messageDOS = getList();
List<File> fileList = new ArrayList<>();
for (MessageDO messageDO : messageDOS) {
File file = FileUtil.getFileByUrl(messageDO.getUrl());
fileList.add(file);
}
List<String> nameList = Arrays.asList(" picture 1", " picture 2", " picture 3", " picture 4", " picture 5");
FileUtil.downZip("record", fileList, nameList, response);
}
Just ask for access .

After unzipping, you can see the picture .
hold excel Files and picture files are packed together into zip
Need to put excel The files and pictures are put in a compressed package , The content is : One excel、 More pictures , In a compressed package file .
Here we are. , In fact, according to the tool class I provided above, you can also guess how to implement . Because I have constantly optimized the tool class .
Ideas :
- export excel To local , Get the local path .
- Download pictures to local , Get the local path .
- Path summary , Export zip file .
That's it excel And pictures url Export of zip Format file .
The specific control end code is as follows :
@GetMapping("exportZip")
public void exportZip(HttpServletResponse response) throws Exception {
List<MessageDO> messageDOS = getList();
if (messageDOS.isEmpty()) {
return;
}
String name = System.currentTimeMillis() + ".xlsx";
String fileName = "D:\\" + name;
ExcelUtils1.export1(fileName, " news ", messageDOS, MessageDO.class);
List<File> fileList = new ArrayList<>();
for (MessageDO messageDO : messageDOS) {
File file = FileUtil.getFileByUrl(messageDO.getUrl());
fileList.add(file);
}
File excelFile = new File(fileName);
fileList.add(excelFile);
List<String> nameList = Arrays.asList(" picture 1", " picture 2", " picture 3", " picture 4", " picture 5", " news excel");
FileUtil.downZip("record", fileList, nameList, response);
}
Calls to perform :

Unzip to see :

thus , This requirement is realized .
Careful friends may find two places :1. excel I used the tools of ExcelUtils1.export1 .2. there excel I specified the path when exporting .
In fact, the export does not change anything , Change to local export , Small partners can realize it by themselves .
The path is specified to obtain the path , You can also use other methods .
At present, it is realized in this way , If there is a better method to optimize later . Friends can also put forward ideas .
边栏推荐
- Moonbeam上的多链用例解析——Derek在Polkadot Decoded 2022的演讲文字回顾
- Overview of Qualcomm 5g intelligent platform
- [search] - iteration deepening / bidirectional dfs/ida*
- Code reading - ten C open source projects
- [hcip] two mGRE networks are interconnected through OSPF (ENSP)
- 活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
- StoneDB 邀请您参与开源社区月会!
- Yocto project download and compilation
- Super technology network security risk assessment service, comprehensively understand the security risks faced by the network system
- Plato launched the LAAS protocol elephant swap, which allows users to earn premium income
猜你喜欢
![[netding cup 2020 rosefinch group]nmap](/img/22/1fdf716a216ae26b9110b2e5f211f6.png)
[netding cup 2020 rosefinch group]nmap

Six noteworthy cloud security trends in 2022

The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities

Reinforcement learning (I): Q-learning, with source code interpretation
![Golang run times undefined error [resolved]](/img/9b/3379aeeff59b47531fe277f7422ce7.png)
Golang run times undefined error [resolved]

Platofarm community ecological gospel, users can get premium income with elephant swap

Top network security prediction: nearly one-third of countries will regulate blackmail software response within three years

TypeError: can only concatenate str (not “int“) to str
![[web technology] 1395 esbuild bundler HMR](/img/74/be75c8f745f18b374ed15c8e1b4466.png)
[web technology] 1395 esbuild bundler HMR

DSP vibration seat
随机推荐
Analyze OP based on autoware_ global_ Planner global path planning module re planning
【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”
Super technology network security risk assessment service, comprehensively understand the security risks faced by the network system
【7.27】代码源 - 【删数】【括号序列】【数字替换】【游戏】【画画】
Leetcode 112: path sum
Autoware reports an error: can't generate global path for start solution
matplotlib中文问题
Some summaries of ibatis script and provider
Network security litigation risk: four issues that chief information security officers are most concerned about
Overview of Qualcomm 5g intelligent platform
【golang】使用select {}
How to protect WordPress website from network attack? It is essential to take safety measures
LeetCode 112:路径总和
JS事件简介
我们总结了 3 大Nacos使用建议,并首次公开 Nacos 3.0 规划图 Nacos 开源 4 周年
Window object of BOM series
[understanding of opportunity-54]: plain book-1-the origin of things [original chapter 1]: the road is simple.
承办首届算力大会,济南胜在何处?
MySQL execution order
For a safer experience, Microsoft announced the first PC with a secure Pluto chip