zoukankan      html  css  js  c++  java
  • spring mvc导出csv案例

    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 = " "; 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; } }
  • 相关阅读:
    极简风格网络消息以及分发架构
    GPS网络时间服务器是如何让集成系统协调工作的?
    北斗授时设备(NTP时间服务器)对高速联网收费的重要性
    卫星互联网路由技术现状及展望
    【Python】获取中国法定节假日的封装
    GCC 内联汇编基础
    MIT6.828——Lab1 partB(麻省理工操作系统课程实验)
    MIT6.828——Lab1 partA(麻省理工操作系统课程实验)
    bochs(2.6.11)配置安装
    MIT6.828(Step0)——实验环境配置
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/14731418.html
Copyright © 2011-2022 走看看