如何为openwith添加下载选项,并在导出文件时将其保存为servlet中的excel

时间:2012-11-21 05:09:32

标签: excel servlets download export-to-excel

Hii伙计!!!                我做了一个应用程序,我需要将数据从数据库导出到.excel formate,其中我已经为生成的.excel文件提供了硬编码路径以保存在系统上的特定位置。现在根据我的要求我需要提供下载选项用于openwith和saveAs从浏览器。 下面我给我的代码.Plz伙计们帮助我...将会感激不尽。提前等待...

String datum1 = request.getParameter("fromdate");
        String datum2 = request.getParameter("todate");
        SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
        Date date = sdfSource.parse(datum1);
        Date date2 = sdfSource.parse(datum2);
        SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
        datum1 = sdfDestination.format(date);
        System.out.println(datum1);
        datum2 = sdfDestination.format(date2);
        System.out.println(datum2);

        String filename = "d:/".concat(datum1).concat(" ").concat("To").concat(" ").concat(datum2).concat(".xls");
        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet sheet = hwb.createSheet("CallBillingSystem");

        HSSFRow rowhead = sheet.createRow((short) 0);
        rowhead.createCell((short) 0).setCellValue("calldate");
        rowhead.createCell((short) 1).setCellValue("src");
        rowhead.createCell((short) 2).setCellValue("dst");

        String strQuery = "";
        ResultSet rs = null;

        conexion conexiondb = new conexion();
        conexiondb.Conectar();

        strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";

        // strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";

        rs = conexiondb.Consulta(strQuery);
        int i = 1;
        while (rs.next()) {
            HSSFRow row = sheet.createRow((short) i);
            row.createCell((short) 0).setCellValue(rs.getString("calldate"));
            row.createCell((short) 1).setCellValue(rs.getString("src"));
            row.createCell((short) 2).setCellValue(rs.getString("dst"));

            i++;
        }
        FileOutputStream fileOut = new FileOutputStream(filename);
        hwb.write(fileOut);
        fileOut.close();
        System.out.println("Your excel file has been generated!");

    } catch (Exception ex) {
        System.out.println(ex);

    }


}

1 个答案:

答案 0 :(得分:1)

您应该在响应标头中使用Content-Disposition

尝试使用此代码

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
                 "attachment;filename=FileName.xls");

OutputStream out = response.getOutputStream();

FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();