/***
* 实现Word模板读取替换内容输出
* @param filePath 模板路径
* @param haderMap 页眉数据
* @param bodyMap 内容数据
* @param footMap 页脚数据
*/
public
static
void
readwriteWord(String filePath, Map<String,String> haderMap,Map<String ,String> bodyMap,Map<String,String> footMap){
//读取word模板
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();
}
//读取word页眉内容
Range harderRange= hdt.getHeaderStoryRange();
//替换word页眉内容
for
(Map.Entry<String, String> entry:haderMap.entrySet()){
harderRange.replaceText(
"${"
+ entry.getKey() +
"}"
, entry.getValue());
}
//读取页脚内容
Range footRange=hdt.getFootnoteRange();
//替换页脚内容
for
(Map.Entry<String,String> entry:footMap.entrySet()){
footRange.replaceText(
"${"
+ entry.getKey().trim() +
"}"
, entry.getValue());
}
//读取word文本内容
Range bodyRange = hdt.getRange();
//替换文本内容
for
(Map.Entry<String,String> entry: bodyMap.entrySet()) {
bodyRange.replaceText(
"${"
+ entry.getKey() +
"}"
,entry.getValue());
}
// PicturesTable picturesTable= hdt.getPicturesTable();
// //hdt.addPicture(bytes, XWPFDocument.PICTURE_TYPE_JPEG);
//
// FileInputStream fis = new FileInputStream("F:\\picture\\http_imgload.jpg");
// //将图片添加到xlsx文件
// int picinx = hdt.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG);
// fis.close();
//
ByteArrayOutputStream ostream =
new
ByteArrayOutputStream();
String fileName =
""
+System.currentTimeMillis();
fileName +=
".doc"
;
FileOutputStream out =
null
;
try
{
out =
new
FileOutputStream(
"E:\\test\\"
+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();
}
}
联系客服