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 = "\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; } }
复制代码

 

posted @   大空白纸  阅读(551)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示