POI读写word模板

原文来自http://www.cnblogs.com/batys/archive/2011/11/24/2262392.html

package com.poi.word;



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 MSWordPoi4 {


/**
* @param args
*/
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("${sub}", "wrjrqwelkrjewlr");
map.put("${item2.school}", "湖南大学");
map.put("${item2.address}", "湖南");
map.put("${item1.name}", "王五1");
map.put("${item1.numberStudent}", "编号002");
map.put("${item1.sex}", "男2");
map.put("${item1.age}", "19");
String srcPath = "e:\\template.doc";
readwriteWord(srcPath, map);
}


/**
* 实现对word读取和修改操作

* @param filePath
*            word模板路径和名称
* @param map
*            待填充的数据,从数据库读取
*/
public static void readwriteWord(String filePath, Map<String, String> map) {
// 读取word模板
// String fileDir = new
// File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();
FileInputStream in = null;
try {
in = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
HWPFDocument hdt = null;
try {
hdt = new HWPFDocument(in);
} catch (IOException e1) {
e1.printStackTrace();
}
Fields fields = hdt.getFields();
Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN)
.iterator();
while (it.hasNext()) {
System.out.println(it.next().getType());
}


// 读取word文本内容
Range range = hdt.getRange();
System.out.println(range.text());
// 替换文本内容
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 = null;
try {
out = new FileOutputStream("E:/" + fileName, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
hdt.write(ostream);
} catch (IOException e) {
e.printStackTrace();
}
// 输出字节流
try {
out.write(ostream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值