Java导出加密的CSV文件
将页面查询(分页查询)的数据导出为csv文件,主要问题还是文件的写入。(这里是生成zip压缩文件,输入的密码才能打开或解压文件)
工具类生成文件
1 public class CSVFileDownloadView extends AbstractFileDownloadView{ 2 @Override 3 protected InputStream getInputStream(Map<String, Object> model, HttpServletRequest request) throws IOException{ 4 InputStream in; 5 //文件名 6 String fileName = (String) model.get("fileName "); 7 //文件内容 8 String fileContent= (String) model.get("fileContent"); 9 ByteArrayOutputStream inMemoryOutputStream = new ByteArrayOutputStream(); 10 //Zip压缩文件(加密)生成 11 ZipOutputStream zos = new ZipOutputStream(inMemoryOutputStream ); 12 // 密码 13 String zipPassword = (String) model.get("zipPassword "); 14 try { 15 ZipParameters parameters = new ZipParameters(); 16 parameters .setCompressionMethod(Zip4jConstans.COMP_DEFLATE); 17 parameters .setCompressionLevel(Zip4jConstans.DEFLATE_LEVEL_NORMAL); 18 parameters .setFileNameINZip(fileName + ".zip"); 19 parameters .setSourceExternalStream(true); 20 parameters .setEncryptFiles(true); 21 parameters .setEncryptionMethod(Zip4jConstans.ENC_METHOD_STANDARD); 22 parameters .setPassword(zipPassword); 23 zos.putNextEntry(null, parameters); 24 //数据写入 25 zos.write(fileContent.getBytes("MS932")); 26 zos.closeEntry(); 27 zos.finish(); 28 zos.close(); 29 in = new ByteArrayOutputStream(inMemoryOutputStream.toByteArray); 30 } catch (ZipException e) { 31 throw new IOException(StringUtils.EMPTY, e); 32 } finally { 33 IOUtils.closeQuietly(zos); 34 IOUtils.closeQuietly(inMemoryOutputStream); 35 } 36 return in; 37 } 38 39 @Override 40 protected void addResponseHeader(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response){ 41 String fileName = (String) model.get("fileName "); 42 response.setCharacterEncoding("utf-8"); 43 response.setHeader("Content-Dispostion", "attachment;" + "filename="+ fileName + ".zip"); 44 response.setContentType("multipart/form-data"); 45 } 46 }
工具类写好,在spring-mvc.xml中配置一下
<bean id="csvFileDownloadView" class="com.jiexlcommon.app.view.CSVFileDownloadView">
OK,接下来是控制层Controller
1 @RequestMapping(value = "csvOutput", method = "RequestMethod.GET") 2 public String csvOutput(Form form, @pageableDefault(size = 10, page = 0) Pageable pageable, Model model){ 3 // 检索条件 4 xxInputBean input = new xxInputBean(); 5 mapper.map(form, input); 6 input.setPageable(pageable); 7 // 通过调用service返回文件名,文件数据内容 8 xxOutputBean output = xxService.csvFileOutput(input); 9 // 设置文件名(自定义) 10 model.addAttribute("fileName", output.getFileName); 11 // (Stiring)fileContent为查询出的数据(在service编辑) 12 model.addAttribute("fileContent", output.getFileContent); 13 // 设置密码(页面输入) 14 model.addAttribute("zipPassword", form.getEnCodePassword); 15 return "csvFileDownloadView"; 16 }
业务层主要是将查询数据按照csv文件要求的格式做编辑,然后返回给controller,这里就不多说了。