正在处理一个需求,有一个word模板,每一段落中都有一些特定字符$value$,我要处理的是把这个$value$替换成具体的数值,然后再输出为word文档,我们选用的是poi3.6,下面是我的部分代码
try
{
OPCPackage pack = POIXMLDocument.openPackage("C:\\workspace\\test.docx");
XWPFDocument doc = new XWPFDocument(pack) ;
Iterator<XWPFParagraph> paragraphIt= doc.getParagraphsIterator();
while (paragraphIt.hasNext())
{
XWPFParagraph paragraph= paragraphIt.next();
if(paragraph.getParagraphText().indexOf("$kvalue$")!=-1)
{
/**替换其中的字符**/
paragraph.getParagraphText().replace("$kvalue$", "AAAAAA"); //问题就在这里替换之后,我如何把这个paragraph重新写回到doc中呢
}
}
FileOutputStream fos = new FileOutputStream("C:\\workspace\\test1.docx");
doc.write(fos);
fos.flush();
fos.close();因为没有找到把替换文字后的paragraph写回到doc中的api,所以输出的word还是原来的模板样式,就是说$value$没有被替换掉,请高手们指点一二啊
try
{
OPCPackage pack = POIXMLDocument.openPackage("C:\\workspace\\test.docx");
XWPFDocument doc = new XWPFDocument(pack) ;
Iterator<XWPFParagraph> paragraphIt= doc.getParagraphsIterator();
while (paragraphIt.hasNext())
{
XWPFParagraph paragraph= paragraphIt.next();
if(paragraph.getParagraphText().indexOf("$kvalue$")!=-1)
{
/**替换其中的字符**/
paragraph.getParagraphText().replace("$kvalue$", "AAAAAA"); //问题就在这里替换之后,我如何把这个paragraph重新写回到doc中呢
}
}
FileOutputStream fos = new FileOutputStream("C:\\workspace\\test1.docx");
doc.write(fos);
fos.flush();
fos.close();因为没有找到把替换文字后的paragraph写回到doc中的api,所以输出的word还是原来的模板样式,就是说$value$没有被替换掉,请高手们指点一二啊
另外3.6对docx格式支持不足,考虑一下新的版本
try
{ OPCPackage pack = POIXMLDocument.openPackage("C:\\workspace\\test.docx"); XWPFDocument doc = new XWPFDocument(pack) ; Iterator<XWPFParagraph> paragraphIt= doc.getParagraphsIterator();
while (paragraphIt.hasNext())
{
XWPFParagraph paragraph= paragraphIt.next();if(paragraph.getParagraphText().indexOf("$kvalue$")!=-1)
{
List<XWPFRun> run=paragraph.getRuns();
for(int i=0;i<run.size();i++)
{
if(run.get(i).getText(run.get(i).getTextPosition())!=null && run.get(i).getText(run.get(i).getTextPosition()).equals("$kvalue$"))
{
/**参数0表示生成的文字是要从哪一个地方开始放置,一开始这里的代码是
* run.get(i).setText("AAAA",run.get(i).getTextPosition());
* 结果AAAA总是添加到要被替换的文字之后,经查看API知道,设置文字从位置0开始
* 就可以把原来的文字全部替换掉了
* */ run.get(i).setText("AAAA",0);
}
}
} }
FileOutputStream fos = new FileOutputStream("C:\\workspace\\test1.docx"); doc.write(fos); fos.flush(); fos.close();