JAVA导出Excel表

来源:互联网 发布:文献法包括网络 编辑:程序博客网 时间:2024/06/07 18:02

导出Excel表

后台代码:

@RequestMapping(value = "/export/createExcel")    public void createExcel(HttpServletResponse response) {        List<Album> albumList = albumService.createExcel();        //创建一个新的Excel        HSSFWorkbook workBook = new HSSFWorkbook();        //创建sheet页        HSSFSheet sheet = workBook.createSheet();        //sheet页名称        workBook.setSheetName(0, "图集信息表");        //创建header页        HSSFHeader header = sheet.getHeader();        //设置标题居中        header.setCenter("标题");        //设置第一行为Header        HSSFRow row = sheet.createRow(0);        HSSFCell cell0 = row.createCell(0);        HSSFCell cell1 = row.createCell(1);        HSSFCell cell2 = row.createCell(2);        HSSFCell cell3 = row.createCell(3);        HSSFCell cell4 = row.createCell(4);        cell0.setCellValue("id");        cell1.setCellValue("name");        cell2.setCellValue("description");        cell3.setCellValue("tags");        cell4.setCellValue("trendId");        if (albumList != null && !albumList.isEmpty()) {            for (int i = 0; i < albumList.size(); i++) {                Album album = albumList.get(i);                row = sheet.createRow(i + 1);                cell0 = row.createCell(0);                cell1 = row.createCell(1);                cell2 = row.createCell(2);                cell3 = row.createCell(3);                cell4 = row.createCell(4);                cell0.setCellValue(album.getId());                cell1.setCellValue(album.getName());                cell2.setCellValue(album.getDescription());                cell3.setCellValue(album.getTags());                cell4.setCellValue(album.getTrendId());                sheet.setColumnWidth(0, 4000);                sheet.setColumnWidth(1, 4000);                sheet.setColumnWidth(2, 4000);                sheet.setColumnWidth(3, 4000);                sheet.setColumnWidth(4, 4000);            }        }        //通过Response把数据以Excel格式保存        response.reset();        response.setContentType("application/msexcel;charset=UTF-8");        try {            response.addHeader("Content-Disposition", "attachment;filename=\""                    + new String(("图集信息表" + ".xls").getBytes("GBK"),                    "ISO8859_1") + "\"");            OutputStream out = response.getOutputStream();            workBook.write(out);            out.flush();            out.close();        } catch (Exception e) {            LOGGER.error("导出失败:", e);        }    }

前台代码:

window.location.href =path +'/girlity/export/createExcel'
原创粉丝点击