1. 程式人生 > 其它 >使用poi建立excel並返回response

使用poi建立excel並返回response

` impl
@Override
public void exportingUserInfo(HttpServletResponse response) throws IOException {

    WritingFileUtils writingFileUtils = new WritingFileUtils();

    String[] nameArray = {"區號","手機號","裝置號"};
    Map<String, List<String>> map = new HashMap<>();
    String filePath ="客戶表測試";

    List<AccountBound> accountBounds = accountBoundMapper.getAccountBound();


    for (AccountBound accountBound : accountBounds) {
        ExportingUserPO exportingUserPO = new ExportingUserPO();
        BeanUtils.copyProperties(accountBound,exportingUserPO);
        List<String> list = new ArrayList<>();
        list.add(0,exportingUserPO.getMobileType().toString());
        list.add(1,exportingUserPO.getMobile());
        list.add(2,exportingUserPO.getPushToken());
        map.put(UUID.randomUUID().toString(),list);
    }
    writingFileUtils.createExcel(response,map,nameArray,filePath);


}`

WritingFileUtils工具類
生成excel
`
public void createExcel(HttpServletResponse response, Map<String, List> map, String[] strArray, String filePath) throws IOException {

    OutputStream out = null;

    // 下面幾行是為了解決檔名亂碼的問題
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    //檔名
    String oriFileName = "客戶表";
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode(oriFileName , "UTF-8").replaceAll("\\+", "%20");
    //生成xlsx格式
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    //生成xls格式
    //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
    //表頭行
    response.setDateHeader("Expires", 0);
    out = response.getOutputStream();

    // 第一步,建立一個webbook,對應一個Excel檔案
    HSSFWorkbook wb = new HSSFWorkbook();
    // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet
    HSSFSheet sheet = wb.createSheet("sheet1");
    sheet.setDefaultColumnWidth(20);// 預設列寬
    // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short
    HSSFRow row = sheet.createRow((int) 0);
    // 第四步,建立單元格,並設定值表頭 設定表頭居中
    HSSFCellStyle style = wb.createCellStyle();
    // 建立一個居中格式
    style.setAlignment(HorizontalAlignment.CENTER);
    //style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    // 新增excel title
    //表頭內容
    HSSFCell cell = null;
    for (int i = 0; i < strArray.length; i++) {
        cell = row.createCell((short) i);
        cell.setCellValue(strArray[i]);
        cell.setCellStyle(style);
    }

    // 第五步,寫入實體資料 實際應用中這些資料從資料庫得到,list中字串的順序必須和陣列strArray中的順序一致
    int i = 0;
    for (String str : map.keySet()) {
        row = sheet.createRow((int) i + 1);
        List<String> list = map.get(str);

        // 第四步,建立單元格,並設定值
        for (int j = 0; j < strArray.length; j++) {
            String value;
            if (j >= list.size()){
                value = "";
            }else {
                value = list.get(j);
            }
            row.createCell((short) j).setCellValue(value);
        }
        i++;
    }

    // 第六步,將檔案存到指定位置
    try {
        wb.write(out);//將Excel用response返回
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}`