java导出word

public void dayinHw(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
Outdoorads od = this.outdooradsService.queryById(id);
HWPFDocument hdt=null;
try {
//第一步读取项目中word模板文件
String fileDir = new File(request.getRealPath("/")+"/doc/").getCanonicalPath();
FileInputStream in = new FileInputStream(new File(fileDir+ "/户外宣传品申请表.doc"));

// 第二步,创建一个HWPFDocument,对应读取的一个doc文件
hdt = new HWPFDocument(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//第三步替换读取到的word模板内容的指定字段
Range range = hdt.getRange();//读取word文本内容
Map<String, String> map = new HashMap<String, String>();//将需要填充的字段放入map中
if(StringUtil.isNotEmpty(od.getTitle())){
map.put("title",od.getTitle());
}else{
map.put("title","");
}
if(od.getConduct_date() != null){
map.put("conduct_date",DateTool.dateToStr1(od.getConduct_date()));
}else{
map.put("conduct_date","");
}
if(StringUtil.isNotEmpty(od.getConduct_address())){
map.put("conduct_address",od.getConduct_address());
}else{
map.put("conduct_address","");
}

for (Map.Entry<String, String> entry : map.entrySet()) {
if(entry.getValue()!=null){
range.replaceText(entry.getKey(), entry.getValue());//替换文本内容
}else{
range.replaceText(entry.getKey(), "");//替换文本内容
}

}
dayin(request, response, hdt);
}
public void dayin(HttpServletRequest request, HttpServletResponse response, HWPFDocument hdt){
//*********************wangyaStart*********************************
try{
//路径
String destPathName = request.getRealPath("/") + "//";
File dirPath = new File(destPathName);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// 生成文件名
String curDate = String.valueOf(new java.util.Date().getTime());
String Filename = dirPath + "//" +"户外宣传品申请表.doc";
//写入数据
FileOutputStream fout = new FileOutputStream(Filename);
hdt.write(fout);
fout.close();

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//输出word内容文件流,提供下载

String fileNameTemp = URLEncoder.encode("户外宣传品申请表.doc", "utf-8");
request.setCharacterEncoding("GBK");
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""+ fileNameTemp + "\"");
OutputStream outs = response.getOutputStream();

bis = new BufferedInputStream(new FileInputStream(Filename));
bos = new BufferedOutputStream(outs);

byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.flush();
bos.close();
}catch(Exception e){
e.printStackTrace();
}
}

posted on 2013-11-15 13:54  lyming  阅读(743)  评论(0)    收藏  举报