java生成word文件

FH-Admin發表於2022-01-04

定義一個工具類wordUtil:

package com.keji.service.utils;

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//from fhadmin.cn
public class docUtil {

    public static XWPFDocument replaceDoc(String srcPath, Map<String, Object> param) {
        try {
            // 讀取word模板
            InputStream fis = new FileInputStream(srcPath);
            XWPFDocument doc = new XWPFDocument(fis);
            //處理段落
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            processParagraph(paragraphList,doc,param);
            //處理表格
            Iterator<XWPFTable> it = doc.getTablesIterator();
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                for (XWPFTableRow row : rows) {
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        List<XWPFParagraph> paragraphListTable =  cell.getParagraphs();
                        processParagraph(paragraphListTable, doc, param);
                    }
                }
            }
            return doc;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void processParagraph(List<XWPFParagraph> paragraphList, XWPFDocument doc, Map<String, Object> param) {
        if(paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String runString = run.toString();
                    Matcher m = Pattern.compile("\\$\\{(.*?)}").matcher(runString);
                    if (m.find()) {
                        boolean isSetText = false;
                        for (Map.Entry<String, Object> entry : param.entrySet()) {
                            String key = entry.getKey();
                            if (runString.indexOf(key) != -1) {
                                isSetText = true;
                                Object value = entry.getValue();
                                if (entry.getValue() == null || entry.getValue().equals("")){
                                    value = "未填寫";
                                }
                                runString = runString.replace(key, value.toString());
                            }
                        }
                        if (isSetText) {
                            run.setText(runString, 0);
                        }
                    }
                }
            }
        }
    }
}

Map<String, Object> map=new HashMap<String, Object>();

//文件裡面的列名為${name}和${sex}

map.put(“${name}”, “姓名”);
map.put(“${sex}”, “性別”);

//檔案位置和map

XWPFDocument doc = docUtil.replaceDoc(“D:\word\month.docx”, map);

//檔案儲存位置

OutputStream os = new FileOutputStream(“D:\tttt.doc”);
doc.write(os);
os.close();
System.out.println(“輸出成功!”);

最後會有一個奇怪的bug,word文件裡的${name}如果是手打上去就可以用,如果是複製上去就會被識別為三個字串,也就是不能替換,當然也有解決方法,可以把全文複製到win自帶的寫字板(不需要調任何格式),
然後把原文刪了複製回來就行了,複製回來之後不能再改欄位了,改了還會出問題,但是可以改樣式什麼的。這個問題不一定會

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章