java實現Excel、xls導出table數據

java實現Excel、xml導出table數據
學習記錄:
不多說直接上代碼

 /**
     * 導出品牌庫
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "exportMyBrandLibrary")
    public void exportEmpoyeeInfo(HttpServletResponse response,String brandStatus) throws IOException{
        response.setCharacterEncoding("UTF-8");
        String[] reportItemName = {"品牌","等級","管理員","今日新增"};
        brandAnalyzes =  brandAnalyzeService.selctBrandAnalyeExce();
        //創建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //創建sheet頁
        HSSFSheet sheet = wb.createSheet("品牌庫信息表");

        //創建標題行
        HSSFRow titleRow = sheet.createRow(0);
        int i = 0;
        for (String s : reportItemName) {
            i++;
            titleRow.createCell(i).setCellValue(s);
        }
        //遍歷將數據放到excel列中
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (BrandAnalyze brandAnalyze : brandAnalyzes) {
            HSSFRow dataResult = sheet.createRow(sheet.getLastRowNum()+1);
            dataResult.createCell(1).setCellValue(brandAnalyze.getBrandName());
            dataResult.createCell(2).setCellValue("核心");//brandAnalyze.getBrandlvStatus();
            dataResult.createCell(3).setCellValue (brandAnalyze.getAdminName() == null ? "空" : brandAnalyze.getAdminName());
            dataResult.createCell(4).setCellValue ((int)Double.parseDouble(brandAnalyze.getTodayAdd()+""));//這個強轉很關鍵,導出數據後因爲不是int類型所以不能進行求和等操作,這個強轉int就是讓數據導出後能進行求和等操作
        }
        // 設置下載時客戶端Excel的名稱   (上面註釋的改進版本,上面的中文不支持)
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String("品牌信息表".getBytes(),"iso-8859-1") + ".xls");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

注意:在前端進行請求導出的時候,別用ajax請求,用a標籤href請求或者用 window.open()請求才能成功!

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