0

嗨伙计们!我做了一个应用程序,我需要将数据库中的数据导出到 .excel 格式中,在其中我为生成的 .excel 文件提供了硬编码路径以保存在系统上的特定位置。现在根据我的要求,我需要提供下载选项用于浏览器中的 openwith 和 saveAs。下面我发布我的代码。请大家帮助我...将不胜感激。提前谢谢...

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);

    }


}
4

1 回答 1

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();
于 2012-11-21T05:17:45.637 回答