1. 程式人生 > >java的excel表格的導出與下載

java的excel表格的導出與下載

ppi etime set des work lena nbsp supported seh

今天做一個java對excel表格的導出和下載的時候,從網絡上搜尋了下載的模板,代碼如下:

控制層:

@RequestMapping(value = "excelOut_identifier")
    public void excelOutIdentifier(HttpServletRequest request, HttpServletResponse response, Long id, ActivationCodeSearchForm searchForm, ExhibitorInfoVenueBranchRelEditForm editForm,
                                   HttpSession session) {
        
try { //獲取數據 List<ActivationCodeDto> list = organizerService.ActivationCodeById(id,searchForm).getRows(); //excel標題 String[] title = {"激活碼","主辦方","創建時間","失效時間"}; //excel文件名 String fileName = "激活碼信息表"+System.currentTimeMillis()+"
.xls"; //sheet名 String sheetName = "激活碼信息表"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String [][] content = new String[title.length][]; for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; ActivationCodeDto obj
= list.get(i); content[i][0] = obj.getActivationCode(); content[i][1] = obj.getExhibitorInfoName(); content[i][2] = sdf.format(obj.getCreateTime()); content[i][3] = sdf.format(obj.getDisabledTime()); } //創建HSSFWorkbook HSSFWorkbook wb = organizerService.excelOutIdentifier(sheetName, title, content, null); this.organizerService.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); }catch(IOException e1) { e1.printStackTrace(); } }

service層:

public  HSSFWorkbook excelOutIdentifier(String sheetName,String []title,String [][]values, HSSFWorkbook wb){
        // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表頭第0行,註意老版本poi對Excel的行數列數有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式

        //聲明列對象
        HSSFCell cell = null;

        //創建標題
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //創建內容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //將內容按順序賦給對應的列對象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

前端:

<button id="js-export" type="button" class="btn btn-primary">導出Excel</button>

jsp:

$(‘#js-export‘).click(function(){
                            window.location.href="${ctxRoot}/admin/organizer/excelOut_identifier.do?id=${id}"
                        });

註意事項:

  一開始我的前端頁面時這樣寫的,是寫的一個ajax請求:

  

<a class="btn btn-success es-ajax"
                                   href="${ctxRoot}/admin/organizer/excelOut_identifier.do?id=${id}">導出excel</a>

  在後端程序都實現可以跑的通的情況下,也沒有什麽日誌錯誤的打印,前端頁面並沒有彈出下載的頁面,然後再網絡上搜索了方法,測試了一遍,都是不行,最後再一篇文章中看到了一個答案,說下載的情況下,使用ajax請求時,是不會彈出下載的頁面出來的,隨即將其修改成window.location.href的請求方式了。果然就解決了這個問題

java的excel表格的導出與下載