使用POI将从数据库搜索出来的记录导出成EXCEL文件并弹出下载框

poi是将数据输出成excel的非常好用的插件,只需要一个poi-3.7.jar的包,就可以完成如题的功能~网上很多是直接导出成excel的例子,而很少弹出下载框让客户下载导出的文件并选择保存路径的功能,所以我将两者整合了一下。

public static void resultSetToExcel(ResultSet rs, String xlsName,
            String sheetName) throws Exception {  //参数分别代表什么意思不用解释了吧~
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0, sheetName);
        HSSFRow row = sheet.createRow((short) 0);
        ;
        HSSFCell cell;
        ResultSetMetaData md = rs.getMetaData();
        int nColumn = md.getColumnCount();
        // 写入各个字段的名称
        for (int i = 1; i <= nColumn; i++) {
            cell = row.createCell((short) (i - 1));
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(md.getColumnLabel(i));
        }

        int iRow = 1;
        // 写入各条记录,每条记录对应Excel中的一行
        while (rs.next()) {
            row = sheet.createRow((short) iRow);
            ;
            for (int j = 1; j <= nColumn; j++) {
                cell = row.createCell((short) (j - 1));
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                if (rs.getObject(j) != null)
                    cell.setCellValue(rs.getObject(j).toString());
                else
                    cell.setCellValue("");
            }
            iRow++;
        }
        String realPath = ServletActionContext.getRequest().getRealPath("/xls");
        xlsName=URLDecoder.decode(xlsName,"utf-8");
        FileOutputStream fOut = new FileOutputStream(realPath + "/" + xlsName);
        workbook.write(fOut);
        fOut.flush();
        fOut.close();

        // 先建立一个文件读取流去读取这个临时excel文件
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(realPath + "/" + xlsName);
        } catch (FileNotFoundException e) {
            return;
        }
        // 设置响应头和保存文件名
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("APPLICATION/OCTET-STREAM");
        String excelName = null;
        try {
            excelName = URLEncoder.encode(xlsName, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
        }
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + excelName + "\"");
        // 写出流信息
        int b = 0;
        try {
            PrintWriter out = response.getWriter();
            while ((b = fs.read()) != -1) {
                out.write(b);
            }
            fs.close();
            out.close();
        } catch (Exception e) {
        }
        File file = new File(realPath + "/" + xlsName);
        if (file.isFile() & file.exists())
            file.delete();
    }

思路简单来说,就是先将生成的excel文件导出到服务器-下载文件-删除服务器上的文件,感觉是不是好理解得多~

原文地址:https://www.cnblogs.com/blairsProgrammer/p/3568268.html