利用POI 技术动态替换word模板内容

项目中需要实现一个功能,动态替换给定模板里面的内容,生成word文档提供下载功能。

中间解决了问题有:

1.页眉的文档logo图片解决,刚开始的时候,HWPFDocument 对象无法读取图片对象(已测试)

2.文档的水印也无法读取

3.下载的乱码问题(火狐浏览器)

4.将文档中的阿拉伯数字的金额改为中文繁体显示

 

 

 

具体代码如下:

/**
* 拍卖结算之后,进行成交确认书的下载操作方法
*
* @param id
* @param response
*/
@RequestMapping(value="/aucLotDownLoad",method = RequestMethod.GET)
@ResponseBody
public void aucLotDownLoad(String id,HttpServletResponse response) {
if (logger.isDebugEnabled()) {
logger.debug("aucLotQuery, aucLotId ", id);
}
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AucLot aucLot = aucLotRepository.findOne(id);
AucBrand aucBrand = aucBrandRepository.findOneByAucLotAndIsBailPayedAndIsDealAndIsSettled(aucLot,AucBrand.AUCBRAND_ISBAILPAYED_YES,AucBrand.AUCBRAND_ISDEAL_SUCCESS,AucBrand.AUCBRAND_ISSETTLED_YES);
if (aucBrand != null) {
String goodsName = aucLot.goodsName();//标的名称
String brandNo = aucBrand.brandNo();//买受人号牌,竞买代码
Date startTime = aucLot.startTime();//拍卖开始时间
Date endTime = aucLot.endTime();//拍卖结束时间
BigDecimal dealPrice = aucBrand.dealPrice();//拍卖成交金额
BigDecimal clientCommison = aucLot.clientCommison();//委托佣金

//定义成交价和委托佣金的总和(两种方式体现)
BigDecimal totalPrice = dealPrice.add(clientCommison);//合计拍卖的总金额

try {
//获取模板文件的目录地址
String fileDir = new File(base.getFile(), "../../../../../../doc/").getCanonicalPath();
//获取模板文件
File demoFile=new File(fileDir + "/1.doc");

FileInputStream in = new FileInputStream(demoFile);
HWPFDocument hdt = new HWPFDocument(in);
//替换读取到的word模板内容的指定字段
Range range = hdt.getRange();
Map<String, String> map = new HashMap<String, String>();
map.put("$PMBD$", goodsName);
map.put("$PMKSSJ$", dateFormater.format(startTime));
map.put("$MSRHP$", brandNo);
map.put("$PMCJJ$", numberToHanZiUtility.number2CNMontrayUnit(dealPrice));
map.put("$PMYJ$", numberToHanZiUtility.number2CNMontrayUnit(clientCommison));
map.put("$HJ$", numberToHanZiUtility.number2CNMontrayUnit(totalPrice));
map.put("$PMCJJXX$", dealPrice + "");
map.put("$PMYJXX$", clientCommison + "");
map.put("$HJXX$", totalPrice + "");
map.put("$PMJSSJ$", dateFormater.format(endTime));
for (Map.Entry<String,String> entry:map.entrySet()) {
range.replaceText(entry.getKey(),entry.getValue());
}

//输出word内容文件流,提供下载
response.setContentType("application/x-msdownload");
String name = java.net.URLEncoder.encode("成交确认书_"+aucLot.goodsNo()+".doc", "UTF8");
name = new String((name).getBytes("UTF-8"), "ISO-8859-1");
response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+name);
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
ServletOutputStream servletOS = response.getOutputStream();
hdt.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

 

 

 


}

 

posted @ 2016-12-04 19:08  Mr_伍先生  阅读(14734)  评论(3编辑  收藏  举报