`
中华国锋
  • 浏览: 40550 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

POI 3.10版本操作修改word内容

阅读更多

注意,poi的版本为:poi-3.10-FINAL

所用jar包为:commons-codec-1.5.jar

commons-logging-1.1.jar

log4j-1.2.13.jar

poi-3.10-FINAL-20140208.jar

poi-scratchpad-3.10-FINAL-20140208.jar

 

poi下载地址:

http://mirror.bit.edu.cn/apache/poi/release/bin/poi-bin-3.10-FINAL-20140208.zip

 

 

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

 

import org.apache.poi.hwpf.HWPFDocument;

import org.apache.poi.hwpf.model.FieldsDocumentPart;

import org.apache.poi.hwpf.usermodel.Field;

import org.apache.poi.hwpf.usermodel.Fields;

import org.apache.poi.hwpf.usermodel.Range;

 

 

 

 

public class testWord {

 

/**

* @param args

* @throws IOException 

*/

public static void main(String[] args) throws IOException {

//读取word模板

String fileDir = "G:/testDdoc";

FileInputStream in = new FileInputStream(new File(fileDir+"/template.doc"));

HWPFDocument hdt = new HWPFDocument(in);

Fields fields = hdt.getFields();

 

Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();

while(it.hasNext()){

System.out.println(it.next().getType());

}

 

//读取word文本内容

Range range = (Range) hdt.getRange();

System.out.println(((org.apache.poi.hwpf.usermodel.Range) range).text());

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

map.put("name", "条款名称修改");

map.put("qianzi", "陈test");

 

//替换文本内容

for (Map.Entry<String,String> entry: map.entrySet() ) {

range.replaceText(entry.getKey(),entry.getValue());

}

ByteArrayOutputStream ostream = new ByteArrayOutputStream();

String fileName = ""+System.currentTimeMillis();

fileName += ".doc";

FileOutputStream out = new FileOutputStream(fileDir+"/"+fileName,true);

hdt.write(ostream);

//输出字节流

out.write(ostream.toByteArray());

out.close();

ostream.close();

 

}

 

}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics