栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Java替换Word文档模板中的变量

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

用Java替换Word文档模板中的变量

是的,您可以使用Apache-POI做到这一点。您的变量名称必须唯一。看下面的代码

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.apache.poi.hwpf.HWPFdocument;import org.apache.poi.hwpf.usermodel.CharacterRun;import org.apache.poi.hwpf.usermodel.Paragraph;import org.apache.poi.hwpf.usermodel.Range;import org.apache.poi.hwpf.usermodel.Section;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public class HWPFTest {    public static void main(String[] args){        String filePath = "F:\Sample.doc";        POIFSFileSystem fs = null;     try {  fs = new POIFSFileSystem(new FileInputStream(filePath));  HWPFdocument doc = new HWPFdocument(fs); doc = replaceText(doc, "$VAR", "MyValue1"); saveWord(filePath, doc);        }        catch(FileNotFoundException e){ e.printStackTrace();        }        catch(IOException e){ e.printStackTrace();        }    }    private static HWPFdocument replaceText(HWPFdocument doc, String findText, String replaceText){        Range r1 = doc.getRange();        for (int i = 0; i < r1.numSections(); ++i ) {  Section s = r1.getSection(i);  for (int x = 0; x < s.numParagraphs(); x++) {      Paragraph p = s.getParagraph(x);      for (int z = 0; z < p.numCharacterRuns(); z++) {          CharacterRun run = p.getCharacterRun(z);          String text = run.text();         if(text.contains(findText)) {  run.replaceText(findText, replaceText);         }      } }        }         return doc;    }    private static void saveWord(String filePath, HWPFdocument doc) throws FileNotFoundException, IOException{        FileOutputStream out = null;        try{ out = new FileOutputStream(filePath); doc.write(out);        }        finally{ out.close();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569812.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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