[Java] [47] Export data to Excel

Preface:

General background report query page, there will be a feature to export data to Excel table

text:

JS:

window.open ( "back-end interface address");

Controller layer:

@ApiOperation(value = "导出列表")
@RequestMapping(value = "excel/exportExcel", method = RequestMethod.GET)
public void exportExcel(HttpServletResponse response, QueryVo query) {
    this.theService.exportCsvPointList(response, query);
}

Service Layer:

@Override
 public  void exportCsvPointList (the HttpServletResponse Response, QueryVo Query) { 
    String title = "integral Record" ; 
    String fileName = + title ".csv" ; 

    // The query query, the query data corresponding to 
    List <the Entity> List; 

    a LinkedHashMap <String, String> = headMap, new new LinkedHashMap <> (); 
    headMap.put ( "phone", "phone number"); // phone is a field name in the Entity, the phone number for the header name excel table 
    headMap.put ( "name", "name" ); 

    ExportCsvUtil.exportCSV (title, fileName, List, headMap,, Response); 
}

Tools:

ExportCsvUtil

package com.bf.base.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 * 下载CSV文件
 */
public class{ExportCsvUtil
     / ** 
     * @param Response returned body 
     * @param List data set 
     * @param title main title 
     * @param of map object subtitle attribute 
     * @param fileName file name
      * / 

    public  static <T> void exportCSV ( title String,, String fileName, List <T> List, a LinkedHashMap <String, String> Map, the HttpServletResponse Response) { 
        the JSONArray Array = new new the JSONArray ();
         for (T obj: List) { 
            array.add (obj); 
        } 
        
        / / 表格头
        List<String> headList = new ArrayList<>();
        for (Entry<String, String> entry : map.entrySet()) {
            headList.add(entry.getValue());
        }
        
        // 数据
        BufferedWriter csvWtriter = null;
        try {
            List<List<String>> dataList = new ArrayList<List<String>>();
            for (Object obj : array) {
                List<String> rowList = new ArrayList<>();
                JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
                for (Entry<String, String> entry : map.entrySet()) {
                    String value = entry.getValue();
                    String key = entry.getKey();
                    String joValue = jo.get(key) == null ? "" : jo.get(key).toString();
                    rowList.add(joValue);
                }
                dataList.add(rowList);
            }

            // 文件下载,使用如下代码
             response.setContentType("application/csv;charset=gb18030");
             response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
             ServletOutputStream out = response.getOutputStream();
             csvWtriter = new BufferedWriter(new OutputStreamWriter(out, "gb18030"), 1024);

            /*int num = headList.size() / 2;
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < num; i++) {
                buffer.append(" ,");
            }
            csvWtriter.write(buffer.toString() + title + buffer.toString());
            csvWtriter.newLine();write the file header//* /

            
            writeRow(headList, csvWtriter);

            // 写入文件内容
            for (List<String> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
            csvWtriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 写一行数据
     * @param row 数据列表
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        for (String data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }
}

 

Guess you like

Origin www.cnblogs.com/huashengweilong/p/11363547.html