栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 修改word文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 修改word文档

4.1.0


    org.apache.poi
    poi
    ${poi.version}



    org.apache.poi
    poi-ooxml
    ${poi.version}


    org.apache.poi
    poi-scratchpad
    ${poi.version}


    org.apache.poi
    poi-ooxml-schemas
    ${poi.version}


    org.apache.poi
    poi-ooxml-schemas
    ${poi.version}
public static void replaceInPara(XWPFParagraph para, Map params) {
    List runs;
    Matcher matcher;
    runs = para.getRuns();
    for (int i = 0; i < runs.size(); i++) {
        XWPFRun run = runs.get(i);
        String runText = run.toString();
        matcher = matcher(runText);
        for (Map.Entry entry :params.entrySet()){
            if (runText.equals(entry.getKey())){
                runText=entry.getValue();
                para.removeRun(i);
                para.insertNewRun(i).setText(runText);
            }
        }



    }
}

只能修改docx文档,doc文件不支持

InputStream is =this.getClass().getClassLoader().getResourceAsStream("点检模板.docx" );
XWPFDocument doc = new XWPFDocument(is);
//替换表格里面的变量
replaceInTable(doc, params);
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd");
Calendar calendar = Calendar.getInstance(); // get current instance of the calendar
OutputStream os = new FileOutputStream("/"+sportEntiy.getVehicleId()+"-"+formatter.format(calendar.getTime())+".docx");
doc.write(os);
close(os);
close(is);

public static void replaceInTable(XWPFDocument doc, Map params) {
    Iterator iterator = doc.getTablesIterator();
    XWPFTable table;
    List rows;
    List cells;
    List paras;
    while (iterator.hasNext()) {
        table = iterator.next();
        rows = table.getRows();
        for (XWPFTableRow row : rows) {
            cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                paras = cell.getParagraphs();
                for (XWPFParagraph para : paras) {
                    replaceInPara(para, params);
                }
            }
        }
    }
}


public static Matcher matcher(String str) {
    Pattern pattern = Pattern.compile("\$\{(.+?)\}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    return matcher;
}


public static void close(InputStream is) {
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public static void close(OutputStream os) {
    if (os != null) {
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946985.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号