模板导出word表格

参考:https://blog.csdn.net/harry_zh_wang/article/details/61938911

package com.xinjian.x.common.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ExportWord {

    public static void build(File tmpFile, Map<String, String> contentMap, String exportFile) throws Exception {
        FileInputStream tempFileInputStream = new FileInputStream(tmpFile);
        HWPFDocument document = new HWPFDocument(tempFileInputStream);
        // 读取文本内容
        Range bodyRange = document.getRange();
        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }

        //导出到文件
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        document.write(byteArrayOutputStream);
        OutputStream outputStream = new FileOutputStream(exportFile);
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.close();
    }

    public static void main(String[] args) throws Exception{
        String tmpFile = "classpath:word/数据统计模板.doc";
        String expFile = "D:/result2.doc";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("date", "2018-5-22 14:43");
        build(ResourceUtils.getFile(tmpFile),datas,expFile);
    }

    /**
     * word表格导出
     */
    public static void downloadTable(File tmpFile, Map<String, Object> contentMap, HttpServletResponse response) throws Exception {
        FileInputStream tempFileInputStream = new FileInputStream(tmpFile);
        XWPFDocument document = new XWPFDocument(tempFileInputStream);
        //解析替换表格对象
        changeTable(document, contentMap);
        response.reset();
        response.setContentType("application/x-download");
        // 设定输出文件头
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("学生信息分类统计", "UTF-8") +".doc");
        OutputStream out = response.getOutputStream();
        document.write(out);
        out.close();
    }
    /**
     * 替换表格对象方法
     * @param document docx解析对象
     * @param textMap 需要替换的信息集合
     */
    public static void changeTable(XWPFDocument document, Map<String, Object> textMap){
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            //只处理行数大于等于2的表格,且不循环表头
            XWPFTable table = tables.get(i);
            List<XWPFTableRow> rows = table.getRows();
            //遍历表格,并替换模板
            eachTable(rows, textMap);
        }
    }

    /**
     * 遍历表格
     * @param rows 表格行对象
     * @param textMap 需要替换的信息集合
     */
    public static void eachTable(List<XWPFTableRow> rows , Map<String, Object> textMap){
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判断单元格是否需要替换
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        run.setText(changeValue(run.toString(), textMap),0);
                    }
                }
            }
        }
    }
    /**
     * 匹配传入信息集合与模板
     * @param value 模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static String changeValue(String value, Map<String, Object> textMap){
        Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
        for (Map.Entry<String, Object> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = "${"+textSet.getKey()+"}";
            if(value.indexOf(key)!= -1){
                value = textSet.getValue()==null?"":textSet.getValue().toString();
            }
        }
        //模板未匹配到区域替换为空
        if(checkText(value)){
            value = "";
        }
        return value;
    }

    /**
     * 判断文本中时候包含$
     * @param text 文本
     * @return 包含返回true,不包含返回false
     */
    public static boolean checkText(String text){
        boolean check  =  false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;

    }
}

猜你喜欢

转载自blog.csdn.net/zwl18210851801/article/details/80750115
今日推荐