csv生成臨時檔案,供前端下載
@RequestMapping(value = "/exportCsv", method = RequestMethod.GET) public void haha(HttpServletRequest request, HttpServletResponse response) { String realPath = request.getRealPath("/"); // 表格頭 Object[] head = { "日誌編號", "請求型別", "操作名稱", "目標型別", "操作狀態", "操作人", "操作人IP", "操作時間", "事件種類", "風險等級", "行為類別" }; List<Object> headList = Arrays.asList(head);
LogCriteria logCriteria = new LogCriteria(); User u = (User) SecurityUtils.getSubject().getPrincipal(); if (u != null) { Role role = u.getRoles().get(0); logCriteria.setRoleCode(role.getRoleCode()); } List<Log> data = logApi.list(logCriteria); // 資料 List<List<Object>> dataList = new ArrayList<List<Object>>();
List<Object> rowList = null; if (data != null) { for (int i = 0; i < data.size(); i++) { Log log = data.get(i); rowList = new ArrayList<Object>(); rowList.add(log.getId()); rowList.add(log.getRequestType()); rowList.add(log.getOperateName()); rowList.add(log.getTargetType()); rowList.add(log.getOperateStatus()); rowList.add(log.getOperaterName()); rowList.add(log.getOperaterIp()); // rowList.add(TimeFormatUtil.dateToString(log.getOperateTime())); rowList.add(log.getOperateTimeStr()); rowList.add(log.getEventCategory()); rowList.add(log.getRiskLevel()); rowList.add(log.getActionType());
dataList.add(rowList); } } String fileName = "操作記錄.csv";// 檔名稱
File csvFile = null; BufferedWriter csvWtriter = null; try { csvFile = File.createTempFile("操作記錄", ".csv"); File parent = csvFile.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } csvFile.createNewFile(); // csvWtriter = new BufferedWriter(new OutputStreamWriter(new // FileOutputStream(csvFile), "GB2312"), 1024); response.setContentType("application/csv;charset=gb18030"); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); ServletOutputStream out = response.getOutputStream(); csvWtriter = new BufferedWriter(new OutputStreamWriter(out, "GB2312"), 1024); int num = headList.size() / 2; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < num; i++) { buffer.append(" ,"); } //本地下載檔案 csvWtriter.write(buffer.toString() + fileName +buffer.toString()); csvWtriter.newLine();
// 寫入檔案頭部 writeRow(headList, csvWtriter);
// 寫入檔案內容 for (List<Object> row : dataList) { writeRow(row, csvWtriter); } csvWtriter.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvWtriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException { for (Object data : row) { StringBuffer sb = new StringBuffer(); String rowStr = sb.append("\"").append(data).append("\",").toString(); csvWriter.write(rowStr); } csvWriter.newLine(); } 參考部落格:https://www.cnblogs.com/always-online/p/4801015.html