标签:csv COLUMN spring mvc SEPARATOR CSV buf response append
1、controller 导出
@RequestMapping(value = "/exportCSV", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") @ResponseBody public void exportCSV(HttpServletRequest request, HttpServletResponse response) { Gson gson = new Gson(); try { // 读取字符编码 String utf = "UTF-8"; String fileName = "标签查询记录"; String fn = fileName + ".csv"; Movie m = new Movie(); m.setLimit(50); m.setOffset(0); List<Movie> movies = movieService.query(m); // 设置响应 response.setContentType("application/csv;charset=GBK"); response.setCharacterEncoding(utf); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=30"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf)); OutputStream os = response.getOutputStream(); ExportUtil.doExport(movies, os); os.close(); } catch (Exception e) { e.printStackTrace(); } }
2、ExportUtil
package com.hyc.www.utils; import java.io.OutputStream; import java.util.List; import com.hyc.www.pojo.Movie; public class ExportUtil { /** CSV文件列分隔符 */ private static final String CSV_COLUMN_SEPARATOR = ","; /** CSV文件列分隔符 */ private static final String CSV_RN = "\r\n"; public static boolean doExport(List<Movie> dataList, OutputStream os) { try { StringBuffer buf = new StringBuffer(); buf.append("电影名").append(CSV_COLUMN_SEPARATOR); buf.append("导员").append(CSV_COLUMN_SEPARATOR); buf.append("语言").append(CSV_COLUMN_SEPARATOR); buf.append("开放时间").append(CSV_COLUMN_SEPARATOR); buf.append(CSV_RN); if (null != dataList) { // 输出数据 for (int i = 0; i < dataList.size(); i++) { Movie m = dataList.get(i); buf.append(m.getName()).append(CSV_COLUMN_SEPARATOR); buf.append(m.getDirector()).append(CSV_COLUMN_SEPARATOR); buf.append(m.getLanguage()).append(CSV_COLUMN_SEPARATOR); buf.append(m.getOpenday()).append(CSV_COLUMN_SEPARATOR); buf.append(CSV_RN); } } // 写出响应 os.write(buf.toString().getBytes("GBK")); os.flush(); return true; } catch (Exception e) { // logger.error("doExport错误...", e); } return false; } }
标签:csv,COLUMN,spring,mvc,SEPARATOR,CSV,buf,response,append 来源: https://www.cnblogs.com/zoro-zero/p/14731418.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。