javaWeb純文字匯出csv檔案,前面的0消失問題
阿新 • • 發佈:2019-02-12
先上匯出程式碼
String header = "序號,工號,姓名,獎項,獎品名,簽字\r\n"; String comma = ","; @RequestMapping("/exportAllLuckyUser") public void exportAllLuckyUser(HttpServletResponse response) throws IOException { response.setHeader("Content-Disposition", "attachment; filename=LuckyUser.csv"); StringBuilder csv = new StringBuilder(header); List<LuckyUser> list = luckyUserDao.find(Query.build()); int i = 1; for (LuckyUser luckyUser : list) { csv .append(i++) .append(comma) .append("\t").append(luckyUser.getEmployeeNo())// 前面加\t,即tab符 .append(comma) .append(luckyUser.getUsername()) .append(comma) .append(luckyUser.getLevelName()) .append(comma) .append(luckyUser.getPrizeName()) .append(comma) .append(" ") .append("\r\n"); } OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "GBK"); osw.write(csv.toString()); osw.flush(); }
如程式碼所示luckyUser.getEmployeeNo()這句返回員工號,員工號前面有數字0,如001234
在匯出csv時,開啟csv前面的0消失,變成1234.解決辦法是在前面加上\t