1. 程式人生 > >匯出資料為excel

匯出資料為excel

將查詢的結果以excel的格式匯出

框架:springboot(沒有什麼意義,僅記錄一下而已)

呼叫路徑:controller→service

一 controller

@ApiOperation(value="匯出",notes = "common")
@GetMapping("output/exports")
@ResponseBody
@PreAuthorize("isAuthenticated()")
Output  elianDataStandardOutputsExport(HttpServletResponse response, Input input) throws IOException {
    String fileName="excel";
    ExcelOutpt excelOutpt = service.data(input);
   
    response= OutputExcelUtil.responseHttp2007 (response,fileName);
    OutputExcelUtil.createWorkBook2007(excelOutpt).write(response.getOutputStream());
    return new Output();
}

(注:input為查詢條件,比如有個列表,我們根據條件得到查詢結果,然後可以選擇把只匯出被查詢出來的資料,沒有進行查詢時則預設匯出所有資料)

二 service

public ExcelOutpt data(Input input) {
    //在資料庫中根據條件把所有資料查詢出來
    String sql=" select * from table";
   //查出來以後放到輸出類中,輸出類data是一個Data型別的集合
    List<Data> data =repository.list(sql,input,Data.class);
    return dataEncap.transfer(data);
}

三 實體轉換類encap

public static ExcelOutpt transfer(List<Data> data) {
     //設定列名
    String columnNames[] = {"id","name"};
   //每一列對應的欄位名。注意。欄位名一定要和輸入的引數中的data中的欄位名一致
    String[] keys = {"id","name"};
    List<Object[]> list = new ArrayList<Object[]>();
   //遍歷傳過來的集合中的資料
    for (Data datas: data) {
         //new一個物件,把當前被遍歷的物件的值一一按順序賦值給objects
           Object[] objects = new Object[]{
                data.getId(),
                data.getName()
        };
        list.add(objects);
    }
   //建立一個輸出檔案類
    ExcelOutpt excelOutpt = new ExcelOutpt();
  //設定列數等引數
    excelOutpt.setColumnNames(columnNames); 
    excelOutpt.setKeys(keys);
    excelOutpt.setList(list);
    return excelOutpt;
}

---------------------------------------------------

public static HttpServletResponse responseHttp2007(HttpServletResponse response,String fileName)throws IOException {
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes("gbk"), "iso-8859-1"));
    return  response;
}

------------------------------------------------------

/**
     * 建立excel文件,
     * [@param](http://my.oschina.net/u/2303379) list 資料
     * @param
     * @param
     * */
    public static Workbook createWorkBook2007(ExcelOutpt excelOutpt) throws IOException{
        List<Object[]> Object=excelOutpt.getList ();
        String[] keys=excelOutpt.getKeys ();//keys list中map的key陣列集合
        String[] columnNames=excelOutpt.getColumnNames ();//columnNames excel的列名 ExcelOutpt excelOutpt
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>> ();
        Map<String, Object> map = new HashMap<String, Object> ();
        map.put("sheetName", "sheet1");
        list.add(map);
        for (int j = 0; j < Object.size(); j++) {
            Object[] project= Object.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            for(int k = 0; k < keys.length; k++){
                mapValue.put(keys[k], project[k]);
            }
            list.add (mapValue);
        }
        // 建立excel工作簿
        Workbook wb = new SXSSFWorkbook(100);
        Sheet sheet = wb.createSheet("sheetName");//建立新的sheet物件
        int rowNo = 0;      //總行號
//        // 手動設定列寬。第一個引數表示要為第幾列設;,第二個引數表示列的寬度,n為列高的畫素數。
//        for(int i=0;i<keys.length;i++){
//            sheet.setColumnWidth((short) i, (short) (35.7 * 150));
//        }
        // 建立兩種單元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 建立兩種字型
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 建立第一種字型樣式(用於列名)
        f.setFontHeightInPoints((short) 10);
        f.setColor(IndexedColors.BLACK.getIndex());
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // 建立第二種字型樣式(用於值)
        f2.setFontHeightInPoints((short) 10);
        f2.setColor(IndexedColors.BLACK.getIndex());
        // 設定第一種單元格的樣式(用於列名)
        cs.setFont(f);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setAlignment(CellStyle.ALIGN_CENTER);

        // 設定第二種單元格的樣式(用於值)
        cs2.setFont(f2);
        cs2.setBorderLeft(CellStyle.BORDER_THIN);
        cs2.setBorderRight(CellStyle.BORDER_THIN);
        cs2.setBorderTop(CellStyle.BORDER_THIN);
        cs2.setBorderBottom(CellStyle.BORDER_THIN);
        cs2.setAlignment(CellStyle.ALIGN_CENTER);

        //設定列名
        for (int i =0;i<list.size();i++){
            //列印300000條後切換到下個工作表,可根據需要自行拓展,2百萬,3百萬...資料一樣操作,只要不超過1048576就可以
            if(rowNo%300000==0){
                sheet = wb.getSheetAt(rowNo/300000);        //動態指定當前的工作表
            }
            rowNo++;
            if(i==0){
                Row row = sheet.createRow(i);
                for(int j=0;j<columnNames.length;j++){
                    Cell cell = row.createCell(j);
                    cell.setCellValue(columnNames[j]);
                    cell.setCellStyle(cs);
                }
            }else{
                Row row1 = sheet.createRow(i);    //新建行物件
                //設定每行每列的值
                for (int j = 0; j < keys.length; j++) {
                    Cell cell = row1.createCell(j);
                    cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString());
                    cell.setCellStyle(cs2);
                }
            }
        }
        return wb;
    }