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;
        }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章