1. 程式人生 > >barcode4j+Apache POI,批量匯出條形碼圖片到excel

barcode4j+Apache POI,批量匯出條形碼圖片到excel

客戶在業務過程中需要列印條形碼,以便追蹤每個單品。為了符合客戶的條碼印表機格式,採用了barcode4j+Apache POI的模式。

一開始用bufferImg讀圖再轉換成byteArray的方法寫,發現無法批量插入,十幾張條形碼只能顯示為一張。後面採用了不在本地儲存圖片,直接用byteArray寫入,成功。下面是程式碼。

public int getExcel(HttpServletRequest request) throws IOException, IllegalArgumentException, IllegalAccessException {
        List<BarCode> list = getBarCodeByStatus(0);
        if (list != null) {
            FileOutputStream fileOut = null;
            HSSFClientAnchor anchor = null;
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet1 = wb.createSheet("條碼列印");
            HSSFFont hssfFont = wb.createFont();
            hssfFont.setCharSet(HSSFFont.DEFAULT_CHARSET);
            hssfFont.setFontHeightInPoints((short) 12);
            hssfFont.setFontName("宋體");
            sheet1.setDefaultRowHeightInPoints((short) 15);
            //畫圖的頂級管理器,一個sheet只能獲取一個(一定要注意這點)
            HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
            //先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
            fileOut = new FileOutputStream(AppConstants.getUploadedPath(request) + "封裝袋編碼表.xls");
            try {
                int row1 = 8;
                int row2 = 12;
                for (BarCode b : list) {
                    //anchor主要用於設定圖片的屬性
                    anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, row1, (short) 3, row2);
                    anchor.setAnchorType(3);
                    //插入圖片
                    patriarch.createPicture(anchor, wb.addPicture(BarCodeUtil.generateByte(b.getCode()), HSSFWorkbook.PICTURE_TYPE_PNG));
//符合客戶印表機格式,間隔13行
                    row1 += 13;
                    row2 += 13;
                    b.setPrtStatus(1);
                }
                // 寫入excel檔案
                wb.write(fileOut);
                System.out.println("----Excel檔案已生成------");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileOut != null) {
                    try {
                        fileOut.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return 0;
        } else {
            return 1;
        }
    }

需要匯入一個

import org.apache.commons.codec.digest.DigestUtils;

不然會報class not found

barcodeUtil程式碼

package com.xxt.utils;

import org.apache.fop.util.UnitConv;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.*;

public class BarCodeUtil {
    public static File generateFile(String msg, String path) {
        File file = new File(path);
        try {
            generate(msg, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return file;
    }
    /**
     * 生成位元組
     *
     * @param msg
     * @return
     */
    public static byte[] generateByte(String msg) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        generate(msg, ous);
        return ous.toByteArray();
    }

    /**
     * 生成到流
     *
     * @param msg
     * @param ous
     */
    public static void generate(String msg, OutputStream ous) {
        if (StringUtils.isEmpty(msg) || ous == null) {
            return;
        }

        Code39Bean bean = new Code39Bean();

        // 精細度
        final int dpi = 150;
        // module寬度
        final double moduleWidth = UnitConv.in2mm(1.0f / dpi);

        // 配置物件
        bean.setModuleWidth(moduleWidth);
        bean.setWideFactor(3);
        bean.doQuietZone(false);

        String format = "image/png";
        try {

            // 輸出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);

            // 生成條形碼
            bean.generateBarcode(canvas, msg);

            // 結束繪製
            canvas.finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //匯出

}