SpringBoot项目生成二维码,再生成Excel文件导出,亲测采坑

1.项目环境 maven依赖 pom文件

	<!--easypoi-->
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-base</artifactId>
        <version>${easypoi.version}</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId> <!-- 移除 guava 旧版本(16.0.1), 其他jar有高版本依赖。  -->
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-web</artifactId>
        <version>${easypoi.version}</version>
    </dependency>
    <dependency>
        <groupId>cn.afterturn</groupId>
        <artifactId>easypoi-annotation</artifactId>
        <version>${easypoi.version}</version>
    </dependency>
    <!-- 生成二维码工具包 zxing -->
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>javase</artifactId>
    </dependency>

easypoi版本号:<easypoi.version>4.3.0</easypoi.version>,4.4.0有问题,导出excel文件二维码是空白的,亲测,office打开也有问题,建议是用wps打开;

必要的工具类 QrCodeExportExcelUtil.java

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @Author: xyx
 * @Description: TODO
 * @DateTime: 2023/3/8 9:47
 **/
@Slf4j
public class QrCodeExportExcelUtil {

    /**
     * 导出excel
     *
     * @param response HttpServletResponse
     * @param fileName 文件名字
     * @param workbook 通过exportPicture()方法获取
     * @author xieyuanxin
     */
    public static void writeExcel(HttpServletResponse response, String fileName, Workbook workbook) throws Exception {
        // 判断数据
        if (workbook == null) {
            throw new Exception("错误");
        }
        // 重置响应对象
        response.reset();
        try {
            OutputStream outputStream = getOutputStream(fileName, response);
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(outputStream);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            outputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 导出文件时为Writer生成OutputStream
     *
     * @param fileName 文件名字
     * @param response response
     * @return 输出流
     * @author xyx
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!");
        }
    }

    /**
    * @Author: xyx
    * @Description: 生成二维码字节流
    * @DateTime: 14:11 2023/3/8
    * @Params: [qrCodeUrl]
    * @Return byte[]
    */
    public static byte[] createQrCodeBytes(String qrCodeUrl){
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 150, 150);
        } catch (WriterException e1) {
            e1.printStackTrace();
        }
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        return QrCodeExportExcelUtil.imageToBytes(image);
    }

    /**
     * BufferedImage转byte[]
     *
     * @param bImage BufferedImage对象
     * @return byte[]
     */
    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "png", out);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return out.toByteArray();
    }
}

导出实体对象 MchExportExcel .java

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

/**
 * 商户信息导出
 *
 * @author xyx
 * @date 2023/3/6 10:07
 */
@Data
@ExcelTarget(value = "MchExportExcelModel")
public class MchExportExcel {

    @Excel(name = "合同码", type = 2, width = 20, height = 20, imageType = 2)
    private byte[] contractCode;

    @Excel(name = "微信认证码", type = 2, width = 20, height = 20, imageType = 2)
    private byte[] wxPayAuthCode;

    @Excel(name = "支付宝认证码", type = 2, width = 20, height = 20, imageType = 2)
    private byte[] aliPayAuthCode;

    @Excel(name = "商户号", width = 15)
    private String mchNo;
}

核心方法

@GetMapping(value = "/export")
public void export() throws Exception{
   	IPage<MchApplyment> pages = mchApplymentService.page(getIPage(), new LambdaQueryWrapper<MchApplyment>() );
   	try {
        List<MchApplymentExportExcel> newList = new ArrayList<>();
        for (MchApplyment mchApplyment : pages.getRecords()) {
            MchApplymentExportExcel exportExcel = new MchApplymentExportExcel();
            DgpayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
            BeanUtils.copyProperties(mchApplyment, exportExcel);
            
            // 调起接口获取签约信息
            ApplymentSignInfo signInfo = isvmchApplymentService.signInfo(mchApplyment);
            // 将返回的url字符串生成二维码
            exportExcel.setContractCode(QrCodeExportExcelUtil.createQrCodeBytes(signInfo.getSignUrl()));
            
            // 调起接口获取微信配置信息 这个调用微信接口返回是base64字符串有点不太一样,需要做个解析处理,转出字节流
            ApplymentSignInfo wxApplymentSignInfo = isvmchWxConfigService.wxOpenSignInfo(mchApplyment);
            byte[] pngs = Base64.getDecoder().decode(wxApplymentSignInfo.getSignUrl());
            exportExcel.setWxPayAuthCode(pngs);
  
            // 调起接口获取支付宝配置信息
          	ApplymentSignInfo alipayApplymentSignInfo = isvmchAlipayConfigService.alipayOpenSignInfo(mchApplyment);
            exportExcel.setAliPayAuthCode(QrCodeExportExcelUtil.createQrCodeBytes(alipayApplymentSignInfo.getSignUrl()));
            newList.add(exportExcel);
        }
        // excel输出
        QrCodeExportExcelUtil.writeExcel(response, title, ExcelExportUtil.exportExcel(new ExportParams("进件统计", "进件统计"), MchApplymentExportExcel.class, newList));
      }catch (Exception e) {
          logger.error("导出excel失败", e);
          throw new BizException("导出订单失败!");
      }
}

效果:

导出效果

打完收工

建议:easypoi有点坑,建议还是用easyExcel好使。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Google开源的Zxing库来生成二维码,以下是基于Spring Boot的批量生成二维码的示例代码: 1. 引入依赖 在pom.xml中添加以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency> ``` 2. 编写生成二维码的工具类 ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QrCodeUtils { private static final int WIDTH = 300; // 二维码宽度 private static final int HEIGHT = 300; // 二维码高度 private static final String FORMAT = "png"; // 二维码格式 private static final String CHARSET = "UTF-8"; // 字符集 private static final int MARGIN = 1; // 边距 /** * 生成二维码 * * @param content 二维码内容 * @param file 二维码文件 * @throws Exception */ public static void generateQRCode(String content, File file) throws Exception { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, getDecodeHintType()); BufferedImage image = toBufferedImage(bitMatrix); ImageIO.write(image, FORMAT, file); } /** * 批量生成二维码 * * @param contents 二维码内容列表 * @param dir 二维码目录 * @throws Exception */ public static void batchGenerateQRCode(List<String> contents, File dir) throws Exception { if (!dir.exists()) { dir.mkdirs(); } for (int i = 0; i < contents.size(); i++) { String content = contents.get(i); String fileName = "qrcode_" + (i + 1) + "." + FORMAT; File file = new File(dir, fileName); generateQRCode(content, file); } } /** * 获取编码提示类型 * * @return */ private static EncodeHintType getDecodeHintType() { EncodeHintType encodeHintType = EncodeHintType.ERROR_CORRECTION; ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.H; return encodeHintType; } /** * BitMatrix转BufferedImage * * @param matrix * @return */ 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) ? 0xFF000000 : 0xFFFFFFFF); } } return image; } } ``` 3. 调用工具类批量生成二维码 ```java import java.io.File; import java.util.ArrayList; import java.util.List; public class QrCodeTest { public static void main(String[] args) throws Exception { List<String> contents = new ArrayList<>(); contents.add("http://www.baidu.com"); contents.add("http://www.google.com"); contents.add("http://www.github.com"); File dir = new File("D:/qrcode"); QrCodeUtils.batchGenerateQRCode(contents, dir); } } ``` 以上代码会在D:/qrcode目录下生成三个二维码文件,内容分别为http://www.baidu.com、http://www.google.com、http://www.github.com。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值