导出包含二维码图片的excel
新建springboot工程,包结构如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>excel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>excel</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 二维码生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
启动类
package com.example.excel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExcelApplication {
public static void main(String[] args) {
SpringApplication.run(ExcelApplication.class, args);
}
}
要导出的bean
package com.example.excel.exportbean;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import lombok.Getter;
import lombok.Setter;
import java.io.File;
/**
* @description 要导出的bean
* @since 2020-11-06 15:02
*/
@Getter
@Setter
@ContentRowHeight(100)
public class PersonBean {
// 姓名
@ExcelProperty("姓名")
private String name;
// 年龄
@ExcelProperty("年龄")
private int age;
// 二维码
@ExcelProperty("二维码")
private File file;
public PersonBean(String name, int age) {
this.name = name;
this.age = age;
}
}
转二维码图片的utils
package com.example.excel.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @description 将指定url转为二维码图片
* @since 2020-11-05 16:58
*/
@Slf4j
public class QRCodeHelper {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public static String createQrCode(String url, String path, String fileName) {
try {
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
File file = new File(path, fileName);
if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
writeToFile(bitMatrix, "jpg", file);
log.info("生成二维码图片:" + file);
return file.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
}
Controller
package com.example.excel.controller;
import com.alibaba.excel.EasyExcelFactory;
import com.example.excel.exportbean.PersonBean;
import com.example.excel.utils.QRCodeHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @description
* @since 2020-11-06 15:11
*/
@Controller
@RequestMapping("/export")
@Slf4j
public class ExportController {
// 要转化成二维码的url前缀
@Value("${qrcode.img.urlContent}")
private String urlContentPrefix;
// 二维码图片磁盘存放地址
@Value("${qrcode.img.baseDir}")
private String qrCodeImgBaseDir;
// 二维码图片集合,存放每次导出时生成的二维码图片
private List<File> qRCodeImgList = new ArrayList<>();
/**
* @description 导出带二维码图片的excel
* @author liujy
* @date 2020/11/6 15:35
*/
@GetMapping(value = "/e")
public void export(final HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
List<PersonBean> beanList = mock();
if (!CollectionUtils.isEmpty(beanList)) {
beanList.forEach(bean -> {
// 将指定url转为二维码图片
String qrCodeImgPath = QRCodeHelper.createQrCode(urlContentPrefix + bean.getName(), qrCodeImgBaseDir, bean.getName() + ".jpg");
File file = new File(qrCodeImgPath);
bean.setFile(file);
// 将图片放进二维码图片集合
qRCodeImgList.add(file);
});
}
final ClassPathResource resource = new ClassPathResource("template/person.xlsx");
EasyExcelFactory.write(response.getOutputStream(), PersonBean.class)
.withTemplate(resource.getInputStream())
.sheet("设备编码")
.doWrite(beanList);
} catch (IOException e) {
response.reset();
response.setContentType("application/json");
log.error("导出异常");
log.error("" + e);
response.setCharacterEncoding("utf-8");
} finally {
// 删除磁盘中的文件
qRCodeImgList.forEach(img -> {
img.delete();
log.info("删除二维码图片成功:" + img);
});
qRCodeImgList.clear();
}
}
/**
* @description 生成模拟数据
* @date 2020/11/6 15:31
*/
private List<PersonBean> mock() {
List<PersonBean> list = new ArrayList<PersonBean>() {{
add(new PersonBean("张三", 17));
add(new PersonBean("tom", 18));
add(new PersonBean("拉布拉多", 19));
}};
return list;
}
}
yml
qrcode:
img:
# 二维码图片磁盘存放地址
baseDir: D:/
# 要转化成二维码的url前缀
urlContent: "welcom"
注意不要忘记上传excel模板
使用postman测试后,可以下载导出的文件
效果如下: