@Override public String downModelXlsFile(SxSourceReq param, HttpServletResponse response) {
//設置響應編碼 response.setCharacterEncoding("GBK"); response.setContentType("multipart/form-data"); ImModSourceVo imModSourceVo = findDetail(param); //ImModSourcePojo imModSourcePojo = imModSourcePojoMapper.get(param.getModSourceId()); if (imModSourceVo == null) { return ReturnJsonFormatUntil.json(false, "該模板不存在!!!"); } boolean isCustom = "2".equals(imModSourceVo.getModType()); //List<ImModSourceSheetPojo> modSourceSheetPojos = imModSourceSheetPojoMapper.findList(param); if ((imModSourceVo.getList() == null || imModSourceVo.getList().size() == 0) && !isCustom) { return ReturnJsonFormatUntil.json(false, "該模板,沒有sheet信息!!!"); } if (!isCustom) { List<ImImpSourceSheetFactorPojo> factorPojoList = imImpSourceSheetFactorPojoMapper.findListBySheetIds(param); Map<String,List<ImImpSourceSheetFactorPojo>> sheetFactorListMap = factorPojoList.stream().collect(Collectors.groupingBy(ImImpSourceSheetFactorPojo::getModSourceSheetId)); List<Map<String,Object>> sheetData = new ArrayList<>(imModSourceVo.getList().size()); Map<String, Object> sheetMap = null; List<List<Map<String,Object>>> dataRowList = null; ImModSourceSheetVo sheetParam = new ImModSourceSheetVo(); List<ImShowFactorColumnPojo> showFactorColumnPojos = getOrderImShowFactorColumnPojos(sheetParam); for (ImModSourceSheetVo imModSourceSheetVo:imModSourceVo.getList()) { sheetMap = new HashMap<>(3); sheetMap.put("sheetIndex",imModSourceSheetVo.getSheetIndex()); sheetMap.put("sheetName",imModSourceSheetVo.getModSourceSheetName()); List<ImModTableUnitVo> tableUnitIndexList = imModSourceSheetVo.getList(); tableUnitIndexList.stream().sorted(Comparator.comparing(ImModTableUnitVo::getCoordinateY)); dataRowList = new ArrayList<>(tableUnitIndexList.size()+1); List<Map<String,Object>> headers = new ArrayList<>(); List<ImModSourceSheetFactorVo> sheetFactorPojos = null; if (ObjectsUtil.isNotEmpty(imModSourceSheetVo.getFactorList())) { sheetFactorPojos = imModSourceSheetVo.getFactorList(); } else { ListUtils.copyList(showFactorColumnPojos,sheetFactorPojos,ImModSourceSheetFactorVo.class); } sheetFactorPojos.stream().sorted(Comparator.comparing(ImImpSourceSheetFactorPojo::getOrderBy)); Map<String,Object> header = null; Set<String> sortKeys = new HashSet<>(); for (ImImpSourceSheetFactorPojo sheetFactorPojo : sheetFactorPojos) { header = new HashMap<>(1); header.put("value",sheetFactorPojo.getFactorPropertyName()); sortKeys.add(sheetFactorPojo.getFactorName()); headers.add(header); } dataRowList.add(headers); /* header.put("value","序號"); headers.add(header); header = new HashMap<>(1); header.put("value","指標名稱"); headers.add(header); header = new HashMap<>(1); header.put("value","單位"); headers.add(header); header = new HashMap<>(1); header.put("value","本期上報值"); headers.add(header); header = new HashMap<>(1); header.put("value","備注說明"); headers.add(header);*/ List<Map<String,Object>> cellList = null; Map<String,Object> cellMap = null; if (ObjectsUtil.isNotEmpty(imModSourceSheetVo.getList())) { for (ImModTableUnitVo imModTableUnitVo : tableUnitIndexList) { cellList = new ArrayList<>(5); cellMap = new HashMap<>(1); for (String sortKey : sortKeys) { if ("indexName".equals(sortKey)) { cellMap.put("value",imModTableUnitVo.getValue()); } else if ("indexUnit".equals(sortKey)) { if (ObjectsUtil.isNotEmpty(imModTableUnitVo.getIndexVo())) { cellMap.put("value",imModTableUnitVo.getIndexVo().getIndexUnit()); } else { cellMap.put("value",""); } } else { cellMap.put("value",""); } cellList.add(cellMap); } /* cellMap.put("value",serial); cellList.add(cellMap); cellMap = new HashMap<>(1); cellMap.put("value",imModTableUnitIndexVo.getIndexName()); cellList.add(cellMap); cellMap = new HashMap<>(1); cellMap.put("value",imModTableUnitIndexVo.getIndexUnit()); cellList.add(cellMap); cellMap = new HashMap<>(1); cellMap.put("value",""); cellList.add(cellMap); cellMap = new HashMap<>(1); cellMap.put("value",imModTableUnitIndexVo.getDescription()); cellList.add(cellMap);*/ //serial++; dataRowList.add(cellList); } } sheetMap.put("data",dataRowList); sheetData.add(sheetMap); } String today = DateUtil.dateToStr(new Date()); String dirPath = IReportUtils.saveXlsFileToLocal(today); //輸出文件到本地 String defaultFileName = DateUtil.getStringAllDate() + ".xls"; File file = new File(dirPath + "/" + defaultFileName); String path = dirPath + File.separator + defaultFileName; response.setHeader("Content-Disposition", "attachment;fileName=" + defaultFileName); ByteArrayOutputStream byteArrayOutputStream = null; try { OutputStream os = response.getOutputStream(); log.info("導出開始!!!"); //outputStream = new BufferedOutputStream(new FileOutputStream(file)); byteArrayOutputStream = new ByteArrayOutputStream(); //ExcelUtil.write2OutputStream(os,sheetData);
//寫文件 ExcelUtil.write2OutputStream(byteArrayOutputStream,sheetData); response.setContentLength(byteArrayOutputStream.size()); ServletOutputStream outputStream = response.getOutputStream(); byteArrayOutputStream.writeTo(outputStream); byteArrayOutputStream.close(); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } log.info("下載文件成功"); String results = ipAddress + path; log.info(results); return ReturnJsonFormatUntil.json(true, results); } else { if (ObjectsUtil.isEmpty(imModSourceVo.getFileId())) { return ReturnJsonFormatUntil.json(false, "沒有該模板文件!!"); } ImFilePojo pojo = imFilePojoMapper.get(imModSourceVo.getFileId()); String filePath = ""; if (ObjectUtils.isEmpty(pojo)) { log.error("查詢的文件為空,不下載"); return ReturnJsonFormatUntil.json(false, "該文件id錯誤,無該文件!!!"); } log.info("開始下載文件到本地"); String fileName = ObjectUtils.isEmpty(pojo.getFileName()) ? UuidUtils.uuid() : pojo.getFileName(); String path = System.getProperty("user.dir"); try { if(!FtpUtil.downloadFileJlf(1,response, ftpConstants.getFTP_HOST_INDEX(), ftpConstants.getFTP_PORT_INDEX(), ftpConstants.getFTP_USER_INDEX(), ftpConstants.getFTP_PASSWORD_INDEX(), pojo.getFilePath(), pojo.getFileName(), "", pojo.getFileName() ) ){ return ReturnJsonFormatUntil.json(false, ResultConstants.DOWNLOAD_FALURE); } //下載路徑 //path = today + "_report/" + defaultFileName; log.info("導出成功!!!"); } catch (Exception e) { log.error("下載失敗+++++++++++++++" + fileName); log.error(e.getMessage()); e.printStackTrace(); return filePath; } log.info("下載文件成功"); String results = ipAddress + path; log.info(results); return ReturnJsonFormatUntil.json(true, results); } }
首先開始設置響應格式
response.setCharacterEncoding("GBK");
response.setContentType("multipart/form-data");
然后設置響應文件名稱
String today = DateUtil.dateToStr(new Date()); String dirPath = IReportUtils.saveXlsFileToLocal(today); //輸出文件到本地 String defaultFileName = DateUtil.getStringAllDate() + ".xls"; File file = new File(dirPath + "/" + defaultFileName); String path = dirPath + File.separator + defaultFileName; response.setHeader("Content-Disposition", "attachment;fileName=" + defaultFileName);
導出文件到本地,並且把輸出流寫入給response
ByteArrayOutputStream byteArrayOutputStream = null; try { OutputStream os = response.getOutputStream(); log.info("導出開始!!!"); //outputStream = new BufferedOutputStream(new FileOutputStream(file)); byteArrayOutputStream = new ByteArrayOutputStream(); //ExcelUtil.write2OutputStream(os,sheetData); ExcelUtil.write2OutputStream(byteArrayOutputStream,sheetData); response.setContentLength(byteArrayOutputStream.size()); ServletOutputStream outputStream = response.getOutputStream(); byteArrayOutputStream.writeTo(outputStream); byteArrayOutputStream.close(); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } log.info("下載文件成功"); String results = ipAddress + path; log.info(results);
return ReturnJsonFormatUntil.json(true, results);
ftp下載xlsx文件代碼為
public static boolean downloadFileJlf(int fileType, HttpServletResponse response, String host, int port, String username, String password, String remotePath, String fileName, String localPath,String saveAsFileName) { int count=0; FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("GBK"); response.setContentType("multipart/form-data"); log.info(host + ":" + port + ":" + username + ":" + ":" + password + ":" + remotePath + ":" + fileName + ":" + localPath + ":" + saveAsFileName +":" + fileType); // // FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); // conf.setServerLanguageCode("zh"); // ftpClient.configure(conf); String fileLastName=""; try { int reply; ftpClient.connect(host, port); ftpClient.login(username, password); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return false; } /* ftpClient.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄 FTPFile[] fs = ftpClient.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].getName().trim().equals(fileName)) { if (fileType==1){ fileLastName=getFileNameNoEx(1,fs[i].getName()); } saveAsFileName = new String(saveAsFileName.getBytes("GB2312"), "ISO-8859-1"); response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName); OutputStream os = response.getOutputStream(); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.retrieveFile(fs[i].getName(), os); os.flush(); os.close(); count++; break; } } */ // FTPFile[] files = ftpClient.listFiles(remotePath); saveAsFileName = new String(saveAsFileName.getBytes("GBK"), "ISO-8859-1"); response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName); OutputStream os = response.getOutputStream(); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.retrieveFile(remotePath+"/"+fileName, os); os.flush(); os.close(); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); return false; } } } return true; }
由於xlsx文件比較特殊,如果還是下載失敗,最后一種笨方法就是把文件下載到服務器本地,每天把文件放入指定文件夾,返回一個可以訪問文件的路徑,讓用戶從本地直接訪問路徑直接下載文件,第二天如果還有人下載文件,創建新文件夾,刪除
昨天的舊文件夾即可,該方法只適用於下載文件比較少的情況,如果文件下載量太大,還是老老實實研究一下怎么下載xlsx文件吧!!!