1. 程式人生 > >List集合匯出成Excel表格-瀏覽器下載

List集合匯出成Excel表格-瀏覽器下載

Excel工具類:

package com.haaa.cloudmedical.common.util;/**
 * Created by Tony.Tong on 2018/9/25.
 */

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExportExcel
 * @Description List集合匯出成Excel表格工具類
 * @Author Tony.Tong
 * @Date 2018/9/25 14:03
 **/
public final class ExportExcel {
    /**
     * 工作簿
     */
    private static HSSFWorkbook workbook;
    /**
     * sheet
     */
    private static HSSFSheet sheet;
    /**
     * 標題行開始的位置
     */
    private static final int TITLE_START_POSITION = 0;
    /**
     * 時間行開始的位置
     */
    private static final int DATEHEAD_START_POSITION = 1;
    /**
     * 表頭行開始的位置
     */
    private static final int HEAD_START_POSITION = 2;
    /**
     * 文字行開始的位置
     */
    private static final int CONTENT_START_POSITION = 3;


    public static ResponseEntity<byte[]> excelExport(List<LinkedHashMap<String,String>> dataList, LinkedHashMap<String, String>
            titleMap, String sheetName, String timeRange, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //初始化workbook
        initHSSFWorkbook(sheetName);
        //填充標題行
        createTitleRow(titleMap, sheetName);
        //填充時間行
        createDateHeadRow(titleMap,timeRange);
        //填充表頭行
        creatHeadRow(titleMap);
        //填充文字內容
        createContentRow(dataList, titleMap);
        //設定列自動伸縮
//        autoSizeColumn(titleMap.size());
        //寫入結果
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        //如果是IE瀏覽器,則用URLEncode解析
        if(isMSBrowser(request)){
            sheetName = URLEncoder.encode(sheetName, "UTF-8");
        }else{//如果是谷歌、火狐則解析為ISO-8859-1
            sheetName = new String(sheetName.getBytes("UTF-8"), "ISO-8859-1");
        }
        //通知瀏覽器以attachment(下載方式)
        headers.setContentDispositionFormData("attachment", sheetName+".xls");
        //application/octet-stream二進位制流資料(最常見的檔案下載)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(out.toByteArray(),headers, HttpStatus.CREATED);
        return filebyte;
    }
    /**
     * @Title initHSSFWorkbook
     * @Description 建立sheet
     * @Date 2018/9/25
     * @Param [sheetName]
     * @Return void
     * @Author Tony.Tong
     */
    private static void initHSSFWorkbook(String sheetName) {
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
    }

    /**
     * @Title createTitleRow
     * @Description 生成標題(第零行建立)
     * @Date 2018/9/25
     * @Param [titleMap, sheetName]表頭名稱,sheet名稱
     * @Return void
     * @Author Tony.Tong
     */
    private static void createTitleRow(Map<String, String> titleMap, String sheetName) {
        CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);
        sheet.addMergedRegion(titleRange);
        HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(sheetName);
    }

    /**
     * @Title createDateHeadRow
     * @Description 建立時間行 (第一行建立)
     * @Date 2018/9/25
     * @Param [titleMap]表頭名稱
     * @Return void
     * @Author Tony.Tong
     */
    private static void createDateHeadRow(Map<String, String> titleMap,String timeRange) {
        CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);
        sheet.addMergedRegion(dateRange);
        HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
        HSSFCell dateCell = dateRow.createCell(0);
        dateCell.setCellValue(timeRange);
    }

    /**
     * @Title creatHeadRow
     * @Description 建立表頭行(第二行建立)
     * @Date 2018/9/25
     * @Param [titleMap]表頭名稱
     * @Return void
     * @Author Tony.Tong
     */
    private static void creatHeadRow(LinkedHashMap<String, String> titleMap) {
        //第一行建立
        HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);
        int i = 0;
        for (String entry : titleMap.keySet()
                ) {
            HSSFCell headCell = headRow.createCell(i);
            headCell.setCellValue(titleMap.get(entry));
            i++;
        }
    }

    /**
     * @Title createContentRow
     * @Description 文字建立
     * @Date 2018/9/25
     * @Param [dataList, titleMap]物件資料集合,表頭資訊
     * @Return void
     * @Author Tony.Tong
     */
    private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {
        try {
           for (int i = 0;i<dataList.size();i++){
               HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);
               Map<String,String> map = (HashMap)dataList.get(i);
               for (int j = 0;j<titleMap.size();){
               for (HashMap.Entry<String, String> entry : map.entrySet()){
                   String value = entry.getValue();
                   HSSFCell textCell = textRow.createCell(j);
                   textCell.setCellValue(value);
                   j++;
               }
               }
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title autoSizeColumn
     * @Description 自動伸縮列 (如非必要,請勿開啟此方法,耗記憶體)
     * @Date 2018/9/25
     * @Param [size]
     * @Return void
     * @Author Tony.Tong
     */
    private static void autoSizeColumn(Integer size) {
        for (int j = 0; j < size; j++) {
            sheet.autoSizeColumn(j);
        }
    }
    /**
     * 方法功能描述: 判斷是否是IE瀏覽器
     * @param request
     * @return
     */
    private static boolean isMSBrowser(HttpServletRequest request) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal)){
                return true;
            }
        }
        return false;
    }
}

Controller:

/**
 * @Title DownloadDoctorWork
 * @Description
 * @Date 2018/9/28
 * @Param [map, request, response]
 * @Return org.springframework.http.ResponseEntity<byte[]>
 * @Author Tony.Tong
 */
@RequestMapping("exportExcel.action")
public ResponseEntity<byte[]> DownloadDoctorWork(@RequestParam Map<String,String> map, HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("start匯出");
    long start = System.currentTimeMillis();
    LinkedHashMap<String, String> titleMap = new LinkedHashMap<>(7);
//此處是自己根據業務場景查詢的表單list,根據自己需求改動即可
    List<LinkedHashMap<String,String>> dataList = userServiceService.findDoctorWorkCountExcel(map);
    ResponseEntity<byte[]> filebyte =null;
    titleMap.put("title_one", "序號");
    titleMap.put("title_two", "健康管家");
    titleMap.put("title_three", "所屬區");
    titleMap.put("title_four", "服務站");
    titleMap.put("title_five", "已服務人數");
    titleMap.put("title_six", "服務人次");
    titleMap.put("title_seven", "服務時長(小時)");
    try {
         filebyte = ExportExcel.excelExport(dataList,titleMap,map.get("sheetName"),map.get("timeRange"),request,response);
    }catch (IOException e){
        e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println("end匯出");
    System.out.println("耗時:"+(end-start)+"s");
   return filebyte;
}

dataList截圖:

dataList截圖

web頁面表單截圖:

web頁面表單截圖

匯出Excel截圖:

EXCEL匯出截圖