jar包中使用freemarker导出excel 解决路径问题

修改ExcelUtil导出方式为流加载而不是通过文件加载.下面贴出ExcelUtil代码

Configuration config = new Configuration();
            InputStream is = null;
            File previewFile = null;
            Reader reader = null;
            try {
                config.setObjectWrapper(new DefaultObjectWrapper());
                config.setDefaultEncoding("utf-8");
                is = getClass().getClassLoader().getResourceAsStream(templateDir+"/"+templateFile);
                previewFile = new File("project-temp/"+docFileName);
                FileUtils.copyInputStreamToFile(is, previewFile);
                reader = new InputStreamReader(new FileInputStream(previewFile), "UTF-8");
                Template template = new Template(docFileName,reader,config);
                if (Excel_2007.equals(version)) {
                    docFileName = docFileName + ".xlsx";
                } else {
                    docFileName = docFileName + ".xls";
                }
               // docFileName = URLEncoder.encode(docFileName, "UTF-8");
                if (!EncodingUtil.getEncoding(docFileName).equals("UTF-8")) {
                    docFileName = URLEncoder.encode(docFileName, "UTF-8");
                }
                OutputStream os = response.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os,"utf-8");
                template.process(beanParams, out);
                response.setContentType("application/force-download");
                docFileName = new String(docFileName.getBytes("UTF-8"), "ISO8859-1");
                response.setHeader("Content-Disposition", "attachment;filename="+docFileName);
                out.flush();
                out.close();
                os.flush();
                os.close();

            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(previewFile != null){
                    previewFile.delete();
                }
            }

 

 

 

 

 

 

 

 

 

posted @ 2019-03-20 10:37  九九离离  阅读(646)  评论(0编辑  收藏  举报