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

我想加载模板Word文档以向其添加内容并另存为新文档。我正在处理.doc文件。

经过长时间的研究,我仅找到docx的解决方案:

http://www.smartjava.org/content/create-complex-word-docx-documents-

programatically-docx4j

http://www.sambhashanam.com/mail-merge-in-java-for-microsoft-word-document-

part-i/

因此,我想将以这种格式编写的任何变量替换为:$VAR它的值。我可以使用Velocity或Apache-

poi做到这一点,什么是最好的解决方案?任何帮助将不胜感激。

回答:

是的,您可以使用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();

}

}

}

以上是 用Java替换Word文档模板中的变量 的全部内容, 来源链接: utcz.com/qa/432956.html

回到顶部