当前位置:网站首页>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 .
边栏推荐
- With the explosive growth of digital identity in 2022, global organizations are facing greater network security
- Autoware reports an error: can't generate global path for start solution
- About df['a column name'] [serial number]
- Data security is a competitive advantage. How can companies give priority to information security and compliance
- Platofarm community ecological gospel, users can get premium income with elephant swap
- Alphafold revealed the universe of protein structure - from nearly 1million structures to more than 200million structures
- 5g commercial third year: driverless "going up the mountain" and "going to the sea"
- 【流放之路-第六章】
- 把逻辑做在Sigma-DSP中的优化实例-数据分配器
- DSP vibration seat
猜你喜欢
![Golang startup error [resolved]](/img/9c/c4757c73d4acd8edf22afa8107fb66.png)
Golang startup error [resolved]

DSP vibration seat

Plato launched the LAAS protocol elephant swap, which allows users to earn premium income

We summarized the three recommendations for the use of Nacos and first published the Nacos 3.0 plan for the 4th anniversary of the open source of Nacos

MySQL execution order

HCIA配置实例(eNSP)

Minimalist thrift+consumer

【Web技术】1395- Esbuild Bundler HMR

HCIA configuration instance (ENSP)

10 major network security incidents in the past 10 years
随机推荐
Golang startup error [resolved]
我们总结了 3 大Nacos使用建议,并首次公开 Nacos 3.0 规划图 Nacos 开源 4 周年
JS 定时器setInterval clearInterval 延时器setTimeOut 异步 动画
【GoLang】同步锁 Mutex
【Web技术】1395- Esbuild Bundler HMR
Analysys analysis: focus on users, improve the user experience of mobile banking, and help the growth of user value
[hcip] experiment of republishing and routing strategy
关于df[‘某一列名’][序号]
【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”
numpy. Where() usage and np.argsort() usage
Golang run times undefined error [resolved]
[网鼎杯 2020 朱雀组]Nmap
承办首届算力大会,济南胜在何处?
ASCII code table
TDA75610-I2C-模拟功放I2C地址的确定
Platofarm community ecological gospel, users can get premium income with elephant swap
Overview of Qualcomm 5g intelligent platform
Reinforcement learning (II): SARS, with code rewriting
Reinforcement learning (I): Q-learning, with source code interpretation
Event express | Apache Doris Performance Optimization Practice Series live broadcast course is open at the beginning. You are cordially invited to participate!