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

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

	
    <dependency>
        <groupId>cn.afterturngroupId>
        <artifactId>easypoi-baseartifactId>
        <version>${easypoi.version}version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guavagroupId>
                <artifactId>guavaartifactId> 
            exclusion>
        exclusions>
    dependency>
    <dependency>
        <groupId>cn.afterturngroupId>
        <artifactId>easypoi-webartifactId>
        <version>${easypoi.version}version>
    dependency>
    <dependency>
        <groupId>cn.afterturngroupId>
        <artifactId>easypoi-annotationartifactId>
        <version>${easypoi.version}version>
    dependency>
    
    <dependency>
        <groupId>com.google.zxinggroupId>
        <artifactId>coreartifactId>
    dependency>
    <dependency>
        <groupId>com.google.zxinggroupId>
        <artifactId>javaseartifactId>
    dependency>

easypoi版本号:4.3.0,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("导出订单失败!");
      }
}

效果:

SpringBoot项目生成二维码,再生成Excel文件导出,亲测采坑_第1张图片

打完收工

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

你可能感兴趣的:(springboot,spring,boot,excel,java)