将列表导出为excel表格

将列表导出为excel表格

本文主要介绍将表格导出为Excel的功能,并且下载时,浏览器提示:


前端HTML导出按钮代码

<a href="javascript:;" onclick="exportList();"></a>

前端js代码

function exportTrackList(){
    window.location.href="/testRequirementTrack/exportList";
}

后台代码

@RequestMapping(value = "/exportList",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
public void exportList(HttpServletResponse response){
    try {
        String[] cellValueArray = {1,2,3,4,5} ;
        String fileName = "数据表";        
        Workbook book = new HSSFWorkbook();
        CellStyle style = book.createCellStyle();  
    style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式 
        Sheet testRequirementTrackSheet = book.createSheet("数据表");  
            Row row = testRequirementTrackSheet.createRow(i);
            for(int j = 0;j<cellValueArray.length;j++){
                row.createCell(j).setCellValue(cellValueArray[j] == null ? "--":cellValueArray[j]);
            }
        response.setCharacterEncoding("UTF-8");
    response.setContentType("application/octet-stream");
    //非IE
        if (request.getHeader("user-agent").toLowerCase().contains("msie")||request.getHeader("user-agent").toLowerCase().contains("like gecko") ) {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GB2312"), "ISO8859-1" ) +".xls"+ "\"");
        }else{
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) +".xls"+ "\"");
        }
        //客户端不缓存   
    response.addHeader("Pargam", "no-cache");   
    response.addHeader("Cache-Control", "no-cache"); 
    OutputStream outputStream = response.getOutputStream(); 
        book.write(outputStream);
        outputStream.flush();   
        outputStream.close(); 
    } catch (Exception e) {
        logger.error(e);
        e.printStackTrace();
    }
}

需要的jar包如下:

poi包

猜你喜欢

转载自blog.csdn.net/juligang320/article/details/78574489