項目中需要實現一個功能,動態替換給定模板里面的內容,生成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();
}
}
}