jsp文件下载 excel导出下载代码及相关问题 - 云起网

云起网

您现在的位置是:首页> Web开发 -> jsp文件下载 excel导出下载代码及相关问题

Article

jsp文件下载 excel导出下载代码及相关问题

云起网2019-04-20 Web开发449
网上下载,直接a链接到文件就可以实现下载,但是这样把文件的路径都暴露了,很多应用场景都不适合这样的方式。下面以java的方式下载文件。


jsp文件下载,适合所有文件,如excel,以byte方式下载。

File file = new File(filePath);
if (file.exists()) {
    try {
        response.reset();
        // 要用servlet 来打开一个 EXCEL 文档,需要将 response 对象中 header 的 contentType 设置成"application/x-msexcel"。
        response.setContentType("application/x-msexcel");
        //response.setContentType("application/vnd.ms-excel");
        // 处理中文文件名
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //servlet中,要在 header中设置下载方式
        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        long fileLength = file.length();
        String length1 = String.valueOf(fileLength);
        response.setHeader("Content_Length", length1);
        //FileInputStream输入流
        //FileInputStream bis = new FileInputStream(file);
        //缓冲流(BufferedStream)可以一次读写一批数据,,缓冲流(Buffered Stream)大大提高了I/O的性能。
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        //OutputStream输出流
        OutputStream bos = response.getOutputStream();

        byte[] buff = new byte[1024];
        int n = 0;
        while ((n = bis.read(buff)) != -1) {
            bos.write(buff, 0, n);
        }

        if (bis != null) {
            bis.close();
        }
        bos.flush();
        if (bos != null) {
            bos.close();
        }
        //out = pageContext.pushBody();
    } catch (Exception e) {
        //logList.add("下载"+filePath+"发生错误:"+e.getMessage());
        //writeLog(logList,"salary","error");
        e.printStackTrace();
    }


jsp导出Excel功能的实现

借助POI的excel接口,可以方便得实现excel导出功能:

首先需要引入poi对应的jar包

import org.apache.poi.hssf.usermodel.*;


 /**
     * 根据列数组和值数组,生成excel文件
     * @param fileRealPath 生成路径
     * @param sheetName
     * @param colList 列数组
     * @param excelList 二维数组,一条记录是一个数组
     * @param strColumn 字符串列的序号,需要区分数字列和字符串列,导出格式区分,如 列1,2
     */
    public void createExcel(String fileRealPath, String sheetName, List<String> colList, List<List<String>> excelList,String strColumn) {
        List<String> logList = new ArrayList<String>();
        OAOperationUtil oaOperationUtil = new OAOperationUtil();
        logList.add("enter createExcel......");
        /* //不写文件了
        FileOutputStream fout = null;
        String realFile = "";
        try {
            File fileWrite = new File(fileRealPath);
            fileWrite.createNewFile();
            fout = new FileOutputStream(fileWrite);
        } catch (Exception e1) {
            logList.add(e1.getMessage() + ":" + realFile);
            oaOperationUtil.writeLog(logList,"salary","error");
        }
        */
        //创建工作簿
        HSSFWorkbook hsshworkbook = new HSSFWorkbook();
        //由工作簿创建工作表,注意的一点是下标从0开始,就像数组一样
        HSSFSheet hsshsheet = hsshworkbook.createSheet();
        
        //设置工作表的名称,该方法需要三个参数,第一个是工作表在工作薄中的位置,第二个就是工作表的名称,第三个是字符编码
        if ("".equals(sheetName)) sheetName = "Sheet1";
        hsshworkbook.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_UTF_16);
        //对应excel的行
        HSSFRow hssfrow = hsshsheet.createRow(0);
        //创建表头 单元格,设置每个单元格的值(作为表头),对应excel的列
        //很多方法的参数是short而不是int,所以需要做一次类型转换
        HSSFCell hssfcell = null;
        HSSFCellStyle headStyle = hsshworkbook.createCellStyle();
        HSSFFont font = hsshworkbook.createFont();
        //font2.setFontName("仿宋_GB2312");
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//粗体显示
        font.setFontHeightInPoints((short) 12);
        headStyle.setFont(font);//选择需要用到的字体格式
        HSSFCellStyle numStyle = hsshworkbook.createCellStyle();
        HSSFDataFormat df = hsshworkbook.createDataFormat();  //此处设置数据格式
        numStyle.setDataFormat(df.getFormat("#,#0.00")); //小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));
        HSSFCellStyle strStyle = hsshworkbook.createCellStyle();
        strStyle.setWrapText(true);

        for (int c = 0; c < colList.size(); c++) {
            hssfcell = hssfrow.createCell((short) c);//, HSSFCell.CELL_TYPE_NUMERIC
            hssfcell.setEncoding(HSSFCell.ENCODING_UTF_16);
            hssfcell.setCellValue(colList.get(c));//设定单元格的值,值的类型有:double,int,String,Date,boolean
            hssfcell.setCellStyle(headStyle);
        }

        //处理后的EXCEL内容结果集
        try {
            logList.add("before getExcelList");
            // 获得处理后的EXCEL内容结果集,excelList存放的是一条条完整的记录
            // arrayList存放的是每一条记录的所有列
            ArrayList arrayList = null;
            //如果excelList没有记录 则返回
            if (excelList.size() < 1) {
                logList.add("没有查询到记录....");
                return;
            }
            if (null != excelList && excelList.size() > 0) {
                //得到结果集的记录条数
                int count = excelList.size();
                logList.add("count:" + count);
                //excelList得到的是含有表头的数据集,i=1表示除去表头后的第一条记录
                for (int i = 0; i < count; i++) {
                    arrayList = (ArrayList) excelList.get(i);
                    hssfrow = hsshsheet.createRow(i + 1);
                    for (int j = 0; j < arrayList.size(); j++) {
                        hssfcell = hssfrow.createCell((short) j, HSSFCell.CELL_TYPE_NUMERIC);
                        hssfcell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        
                        if(j==0) {
                            String money = arrayList.get(j).toString();
                            if("".equals(money)) hssfcell.setCellValue("");
                            else hssfcell.setCellValue(Integer.parseInt(money));
                        }
                        else if((","+strColumn+",").indexOf(","+j+",")>-1){ //j包含在strColumn中,则是字符串列
                            //else if(j==1 ||j==2 || j==9|| j==10 || j==11 ) { //字符串列
                            hssfcell.setCellValue(arrayList.get(j).toString());
                            if(j==1)hssfcell.setCellStyle(strStyle);//利润中心列换行
                        }else {
                            String money = arrayList.get(j).toString();
                            if("".equals(money)) money="0";
                            hssfcell.setCellValue(Double.parseDouble(money));
                            hssfcell.setCellStyle(numStyle);
                        }
                        
                    }
                }
            }
            /* //将工作簿对象hsshworkbook写入到文件输出流
            hsshworkbook.write(fout);
            fout.flush();
            fout.close();
            */
                    OutputStream os = response.getOutputStream();
                    hsshworkbook.write(os);
                    os.flush();
                    os.close();
            logList.add("EXCEL文件已生成......");
        } catch (IOException e) {
            logList.add("createExcel error:" + e.getMessage());
            return;
        }
        logList.add("before DownExcelFile");
        //下载已生成的execl文件
        logList.add("EXCEL文件下载完成......");
    }

下面是调用方式,准备表格的表头和内容数据

List<String> colList = new ArrayList<String>();		
colList.add("序号");
colList.add("姓名");
colList.add("金额");


List<String> columnList = new ArrayList<String>();
columnList.add(rowIndex + "");
columnList.add(rs.getString("name"));
columnList.add(rs.getString("je"));
rowsList.add(columnList);

String fileDownPath = "/tempfile/"+fileName;
String realFile = application.getRealPath(fileDownPath);

oaOperate.createExcel(realFile,"Sheet1",colList,rowsList,"1,2,9,10,11");

上面的代码是直接导出excel,输出流给浏览器。也可以输出文件到服务器路径,见上面代码中注释 部分。

文章评论

共有0条评论来说两句吧...