天天看點

SpringBoot使用Word導出表格WordUtils.java工具類CustomXWPFDocument.java工具類

有這樣的需要,客戶需要把表單資訊導出,上級簽字,這個涉及多行記錄,需要導出word表格

找了很多方法,沒有實作,現在将實作的方法分享出來

隻有兩個工具類,自帶導出測試方法,根據自己需要修改圖檔和模闆路徑即可,親測可用

SpringBoot使用Word導出表格WordUtils.java工具類CustomXWPFDocument.java工具類

WordUtils.java工具類

package com.fc.test.util;
import com.qiniu.util.Json;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用戶端工具類
 * @author zlxls
 * @date: 2020年04月21日 下午2:10:48
 */
public class WordUtils {

    public void exportWordData(HttpServletResponse response){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("${position}", "java開發");
        params.put("${name}", "段然濤");
        params.put("${sex}", "男");
        params.put("${national}", "漢族");
        params.put("${birthday}", "生日");
        params.put("${address}", "許昌");
        params.put("${height}", "165cm");
        params.put("${biYeDate}", "1994-02-03");
        params.put("${landscape}", "團員");
        params.put("${zhuanYe}", "社會工作");
        params.put("${xueLi}", "大學");
        params.put("${school}", "江西科技師範大學");
        params.put("${phone}", "177");
        params.put("${eMail}", "157");
        try{
            Map<String,Object> header = new HashMap<String, Object>();
            header.put("width", 100);
            header.put("height", 150);
            header.put("type", "jpg");
            header.put("content", WordUtils.inputStream2ByteArray(new FileInputStream("C:\\Users\\Administrator\\Desktop\\01.jpg"), true));
            params.put("${header}",header);
            Map<String,Object> header2 = new HashMap<String, Object>();
            header2.put("width", 100);
            header2.put("height", 150);
            header2.put("type", "jpg");
            header2.put("content", WordUtils.inputStream2ByteArray(new FileInputStream("C:\\Users\\Administrator\\Desktop\\01.jpg"), true));
            params.put("${header2}",header2);
            List<String[]> testList = new ArrayList<String[]>();
            testList.add(new String[]{"1","1AA","1BB","1CC"});
            testList.add(new String[]{"2","2AA","2BB","2CC"});
            testList.add(new String[]{"3","3AA","3BB","3CC"});
            testList.add(new String[]{"4","4AA","4BB","4CC"});
            testList.add(new String[]{"5","4AA","4BB","4CC"});
            String path="F:\\JAVAProject\\dh161_appliance\\dh161_appliance\\target\\classes\\static\\tpl\\change_tpl.docx";  //模闆檔案位置
            String fileName= new String("測試文檔.docx".getBytes("UTF-8"),"iso-8859-1");    //生成word檔案的檔案名

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 導出word方法調用
     *
     * @param response
     * @param list 資料集合
     * @param path 模闆路徑
     * @param fileName 導出名稱
     * @param index 表格起始資料行數
     * @param index 是否合并單元格 無法适配,根據數字進行制定合并
     * @throws Exception
     */
    public void exportWord(HttpServletResponse response,List<String[]> list,String path,String fileName,int index,int isMerge) throws Exception{
        Map<String, Object> params = new HashMap<String, Object>();
        exportWord(response,list,path,fileName,index,params,isMerge);
    }
    /**
     * 導出word方法調用
     *
     * @param response
     * @param list 資料集合
     * @param path 模闆路徑
     * @param fileName 導出名稱
     * @param index 表格起始資料行數
     * @throws Exception
     */
    public void exportWord(HttpServletResponse response,List<String[]> list,String path,String fileName,int index) throws Exception{
        Map<String, Object> params = new HashMap<String, Object>();
        exportWord(response,list,path,fileName,index,params,0);
    }
    /**
     * 導出word方法調用
     *
     * @param response
     * @param list 資料集合
     * @param path 模闆路徑
     * @param fileName 導出名稱
     * @param index 表格起始資料行數
     * @param params 要替換的資料
     * @param isMerge 是否合并單元格 無法适配,根據數字進行制定合并
     * @throws Exception
     */
    public void exportWord(HttpServletResponse response,List<String[]> list,String path,String fileName,int index,Map<String, Object> params,int isMerge) throws Exception{
        getWord(response,list,path,fileName,index,params,isMerge);
    }
    /**
     * 根據模闆生成word
     *
     * @param path 模闆的路徑
     * @param params 需要替換的參數
     * @param list 需要插入的參數
     * @param fileName 生成word檔案的檔案名
     * @param response
     * @param index 清單資料起始行數
     * @throws Exception
     */
    public void getWord(HttpServletResponse response,List<String[]> list,String path,String fileName,int index,Map<String, Object> params,int isMerge) throws Exception {
        fileName= new String((fileName+".docx").getBytes("UTF-8"),"iso-8859-1");    //生成word檔案的檔案名
        File file = new File(path);
        InputStream is = new FileInputStream(file);
        CustomXWPFDocument doc = new CustomXWPFDocument(is);
        if(params.size()>0){
            this.replaceInPara(doc, params);    //替換文本裡面的變量
        }
        this.replaceInTable(doc, params, list,index,isMerge); //替換表格裡面的變量
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        doc.write(os);
        this.close(os);
        this.close(is);
    }
    /**
     * 替換表格裡面的變量
     *
     * @param doc 要替換的文檔
     * @param params 參數
     * @param tableList 資料清單
     * @param index 有效行數
     * @param isMerge 是否合并單元格 無法适配,根據數字進行制定合并
     */
    private void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params, List<String[]> tableList,int index,int isMerge) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        int indexRow = 0;
        while (iterator.hasNext()) {
            table = iterator.next();
            if (table.getRows().size() > 1) {
                //判斷表格是需要替換還是需要插入,判斷邏輯有$為替換,表格無$為插入
                if (this.matcher(table.getText()).find()) {
                    rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            paras = cell.getParagraphs();
                            for (XWPFParagraph para : paras) {
                                this.replaceInPara(para, params, doc);
                            }
                        }
                    }
                } else {
                    insertTable(table, tableList,index,isMerge);  //插入資料
                }
            }
        }
    }
    /**
     * 為表格插入資料,行數不夠添加新行
     *
     * @param table 需要插入資料的表格
     * @param tableList 插入資料集合
     * @param index 插入資料集合
     * @param isMerge 是否合并單元格 無法适配,根據數字進行制定合并
     */
    private static void insertTable(XWPFTable table, List<String[]> tableList,int index,int isMerge) {
        //建立行,根據需要插入的資料添加新行,不處理表頭
        for (int i = 0; i < tableList.size(); i++) {
            XWPFTableRow row = table.createRow();
        }
        //周遊表格插入資料
        List<XWPFTableRow> rows = table.getRows();
        int lengthI = tableList.size();
        for (int i = 0; i < lengthI; i++) {
            List<XWPFTableCell> cells = table.getRow(i+index).getTableCells();
            int lengthJ = tableList.get(i).length;
            for (int j = 0; j < lengthJ; j++) {
                XWPFTableCell cell = cells.get(j);
                String s = tableList.get(i)[j];
                cell.setText(s);
            }
        }
        //以下是合并單元格
        if(isMerge==1){
            int fromCell =3;
            int toCell =5;
            for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
                XWPFTableCell cell = table.getRow(0).getCell(cellIndex);
                if ( cellIndex == fromCell ) {
                    // The first merged cell is set with RESTART merge value
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                } else {
                    // Cells which join (merge) the first one, are set with CONTINUE
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                }
            }
            fromCell =6;
            toCell =8;
            for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
                XWPFTableCell cell = table.getRow(0).getCell(cellIndex);
                if ( cellIndex == fromCell ) {
                    // The first merged cell is set with RESTART merge value
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                } else {
                    // Cells which join (merge) the first one, are set with CONTINUE
                    cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                }
            }
        }
    }
    /**
     * 替換段落裡面的變量
     *
     * @param doc    要替換的文檔
     * @param params 參數
     */
    private void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            this.replaceInPara(para, params, doc);
        }
    }
    /**
     * 替換段落裡面的變量
     *
     * @param para   要替換的段落
     * @param params 參數
     */
    private void replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc) {
        List<XWPFRun> runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int start = -1;
            int end = -1;
            String str = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start != -1)) {
                    str += runText;
                }
                if ('}' == runText.charAt(runText.length() - 1)) {
                    if (start != -1) {
                        end = i;
                        break;
                    }
                }
            }

            for (int i = start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
            }

            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                if (str.indexOf(key) != -1) {
                    Object value = entry.getValue();
                    if (value instanceof String) {
                        str = str.replace(key, value.toString());
                        para.createRun().setText(str, 0);
                        break;
                    } else if (value instanceof Map) {
                        str = str.replace(key, "");
                        Map pic = (Map) value;
                        int width = Integer.parseInt(pic.get("width").toString());
                        int height = Integer.parseInt(pic.get("height").toString());
                        int picType = getPictureType(pic.get("type").toString());
                        byte[] byteArray = (byte[]) pic.get("content");
                        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                        try {
                            //int ind = doc.addPicture(byteInputStream,picType);
                            //doc.createPicture(ind, width , height,para);
                            doc.addPictureData(byteInputStream, picType);
                            doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
                            para.createRun().setText(str, 0);
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    /**
     * 正則比對字元串
     *
     * @param str
     * @return
     */
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }
    /**
     * 根據圖檔類型,取得對應的圖檔類型代碼
     *
     * @param picType
     * @return int
     */
    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }
    /**
     * 将輸入流中的資料寫入位元組數組
     *
     * @param in
     * @return
     */
    public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isClose) {
                try {
                    in.close();
                } catch (Exception e2) {
                    e2.getStackTrace();
                }
            }
        }
        return byteArray;
    }
    /**
     * 關閉輸入流
     *
     * @param is
     */
    private void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 關閉輸出流
     *
     * @param os
     */
    private void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

CustomXWPFDocument.java工具類

package com.fc.test.util;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import java.io.IOException;
import java.io.InputStream;

/**
 * 用戶端工具類
 * @author zlxls
 * @date: 2020年04月21日 下午2:10:48
 */
public class CustomXWPFDocument extends XWPFDocument {

    public CustomXWPFDocument(InputStream in) throws IOException {
        super(in);
    }

    public CustomXWPFDocument() {
        super();
    }

    public CustomXWPFDocument(OPCPackage pkg) throws IOException {
        super(pkg);
    }

    /**
     * @param id
     * @param width 寬
     * @param height 高
     * @param paragraph  段落
     */
    public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        String blipId = getAllPictures().get(id).getPackageRelationship().getId();
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
        String picXml = ""
                +"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                +"   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                +"      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                +"         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                + id
                +"\" name=\"Generated\"/>"
                +"            <pic:cNvPicPr/>"
                +"         </pic:nvPicPr>"
                +"         <pic:blipFill>"
                +"            <a:blip r:embed=\""
                + blipId
                +"\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                +"            <a:stretch>"
                +"               <a:fillRect/>"
                +"            </a:stretch>"
                +"         </pic:blipFill>"
                +"         <pic:spPr>"
                +"            <a:xfrm>"
                +"               <a:off x=\"0\" y=\"0\"/>"
                +"               <a:ext cx=\""
                + width
                +"\" cy=\""
                + height
                +"\"/>"
                +"            </a:xfrm>"
                +"            <a:prstGeom prst=\"rect\">"
                +"               <a:avLst/>"
                +"            </a:prstGeom>"
                +"         </pic:spPr>"
                +"      </pic:pic>"
                +"   </a:graphicData>" + "</a:graphic>";

        inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try{
            xmlToken = XmlToken.Factory.parse(picXml);
        }catch(XmlException xe) {
            xe.printStackTrace();
        }
        inline.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("圖檔"+ id);
        docPr.setDescr("測試");
    }
}