word模板生成word文档并下载

控制层:

public void downpact() {
String str=request.getParameter("dId");
String docPath = request.getServletContext().getRealPath("/") + "template";
EmploeeContract emploeeContract=emploeeContractService.get(Long.parseLong(str));
emploeeContractService.downpact(request,response,emploeeContract,docPath);
}

业务层:

@Override
public void downpact(HttpServletRequest request, HttpServletResponse response, EmploeeContract emploeeContract,
String docPath) {
Map<String,Object> dataMap=new HashMap<String,Object>();  
        Company company=companyDAO.get(Long.parseLong(emploeeContract.getContractUnit()));
Dept dept=deptDAO.get(Long.parseLong(company.getName()));
emploeeContract.setContractUnit(dept.getName());
dataMap.put("cname", dept.getName());
dataMap.put("address", company.getPostalAddress());
dataMap.put("code", company.getPostalCode());
dataMap.put("registerAddress", company.getRegisterAddress());
dataMap.put("legal_representative", company.getLegalRepresentative());
StaffFile staffFile=staffFileDAO.get(emploeeContract.getCustomerId());
if(Tools.isValid(staffFile)){
dataMap.put("sname", staffFile.getName());
dataMap.put("gender", DataDictionaryLoad.getText("SEX", staffFile.getGender()));
if(Tools.isValid(staffFile.getIdCard())){
dataMap.put("idCard", staffFile.getIdCardNum());
}else {
dataMap.put("idCard", "");
}
if(Tools.isValid(staffFile.getPostalAddress())){
dataMap.put("saddress", staffFile.getPostalAddress());
}else {
dataMap.put("saddress",  "");
}
if(Tools.isValid(staffFile.getContactPhone())){
dataMap.put("phone", staffFile.getContactPhone());
}else {
dataMap.put("phone",  "");
}
Dept dept2=deptDAO.get(staffFile.getOrgId());
dataMap.put("dept", dept2.getName());
Position position=positionDAO.get(staffFile.getPositionId());
dataMap.put("postion", position.getName());
}
BigDecimal numberOfMoney = new BigDecimal( emploeeContract.getPrice());  
   String s = NumberToCN.number2CNMontrayUnit(numberOfMoney);  
dataMap.put("money", s);
dataMap.put("year1", emploeeContract.getContractPeriod());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy");
SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("MM");
SimpleDateFormat simpleDateFormat3=new SimpleDateFormat("dd");
dataMap.put("year", simpleDateFormat.format(emploeeContract.getSignDate()));
dataMap.put("month", simpleDateFormat2.format(emploeeContract.getSignDate()));
dataMap.put("day", simpleDateFormat3.format(emploeeContract.getSignDate()));
dataMap.put("year2", simpleDateFormat.format(emploeeContract.getBeginDate()));
dataMap.put("month2", simpleDateFormat2.format(emploeeContract.getBeginDate()));
dataMap.put("day2", simpleDateFormat3.format(emploeeContract.getBeginDate()));
dataMap.put("year3", simpleDateFormat.format(emploeeContract.getEndDate()));
dataMap.put("month3", simpleDateFormat2.format(emploeeContract.getEndDate()));
dataMap.put("day3", simpleDateFormat3.format(emploeeContract.getEndDate()));
        // 输出文档路径及名称
        String str1="员工合同"+Math.random()*1000+".doc";
        String templateName="staffFile.xml";
try {
WordPdfUtils.exportMillCertificateWord(request, response,dataMap, docPath, str1, templateName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String docPath,String fileName,String templateName) throws IOException {  
Configuration configuration = null;  
   configuration = new Configuration();  
   configuration.setDefaultEncoding("UTF-8"); 
try {
configuration.setDirectoryForTemplateLoading(new File(docPath));
} catch (IOException e1) {
e1.printStackTrace();
}
Template freemarkerTemplate = configuration.getTemplate(templateName);  
        File file = null;  
        InputStream fin = null;  
        ServletOutputStream out = null;  
        try {  
            // 调用工具类的createDoc方法生成Word文档  
            file = createDoc(map,templateName,freemarkerTemplate);  
            fin = new FileInputStream(file);  
  
            response.setCharacterEncoding("utf-8");  
            response.setContentType("application/msword");  
            // 设置浏览器以下载的方式处理该文件名  
            //String fileName = "材质单"+System.currentTimeMillis()+ ".doc";  
            response.setHeader("Content-Disposition", "attachment;filename="  
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));  
  
            out = response.getOutputStream();  
            byte[] buffer = new byte[512];  // 缓冲区  
            int bytesToRead = -1;  
            // 通过循环将读入的Word文件的内容输出到浏览器中  
            while((bytesToRead = fin.read(buffer)) != -1) {  
                out.write(buffer, 0, bytesToRead);  
            }  
        } finally {  
            if(fin != null) fin.close();  
            if(out != null) out.close();  
            if(file != null) file.delete(); // 删除临时文件  
        }  
    }  
private static File createDoc(Map<?, ?> dataMap,String templateName,Template template) {  
       File f = new File(templateName);  
       Template t = template;  
       try {  
           // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开  
           Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");  
           t.process(dataMap, w);  
           w.close();  
       } catch (Exception ex) {  
           ex.printStackTrace();  
           throw new RuntimeException(ex);  
       }  
       return f;  
   }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值