【问题标题】:how to add openwith and save as dialogue box while exporting to .excel on button click如何在单击按钮时导出到.excel时添加openwith并另存为对话框
【发布时间】:2012-10-30 05:09:47
【问题描述】:

我通过单击按钮将 jqgrid 中显示的数据导出到 .excel 文件中。 这是我的导出到 excel 按钮单击的代码..

 $('#excel').click(function(){
            var fromdate=$('#fromdate').val();
            var todate=$('#todate').val();
            if(fromdate && todate)
            {
                var URL='excel.jsp?fromdate='+$('#fromdate').val()+'&todate='+$('#todate').val();
                $.ajax({
                   url:URL,
                   type:'GET',
                   success:function(data){
                       alert('Exported To Excel');
                   }

                });
            }
        });

现在这个按钮将指向 excel.jsp 页面。下面是我的 excel.jsp 页面代码,它直接给出了将生成的 .excel 文件保存在本地磁盘 D:// 中的路径。现在当用户单击时根据我的需要在导出到 excel 按钮时,应弹出一个打开并另存为对话框,让用户能够提供所需的名称并保存到所需的位置..

excel.jsp

    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:/excel.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");
    rowhead.createCell((short) 3).setCellValue("dstchannel");
    rowhead.createCell((short) 4).setCellValue("lastapp");
    rowhead.createCell((short) 5).setCellValue("duration");
    rowhead.createCell((short) 6).setCellValue("disposition");
    rowhead.createCell((short) 7).setCellValue("amaflags");
    rowhead.createCell((short) 8).setCellValue("cdrcost");


    String strQuery = "";
    ResultSet rs = null;

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

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



    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"));
        row.createCell((short) 3).setCellValue(rs.getString("dstchannel"));
        row.createCell((short) 4).setCellValue(rs.getString("lastapp"));
        row.createCell((short) 5).setCellValue(rs.getString("duration"));
        row.createCell((short) 6).setCellValue(rs.getString("disposition"));
        row.createCell((short) 7).setCellValue(rs.getString("amaflags"));
        row.createCell((short) 8).setCellValue(rs.getString("cdrcost"));
        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);

}

【问题讨论】:

  • 我不知道 java 的实现,所以我没有把它作为答案,但根本不需要向文件系统写入任何内容;可以发送适当的标头并直接在响应中输出内容,并提示用户保存。您可以查看相应的标题并从this answer in PHP 获得想法。
  • Yobo 与 jsp 和 servlet 相关的问题,与 PHP 无关。

标签: java jquery excel dialog


【解决方案1】:

你应该设置几个HTTP头并将Excel文件的内容直接写入HttpServletResponse的OutputStream。

response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Length", String.valueOf(fileSize));
response.addHeader("Content-Disposition", String.format("attachment; filename=%s", fileName));

“Content-Type”标头告诉您要发送到浏览器的流类型。 Mime 类型取决于 Excel 文件的格式。见What is correct content-type for excel files?

“Content-Length”不是强制性的,但它允许浏览器显示下载进度。

“Content-Disposition”告诉浏览器初始文件名另存为(不带路径)。

响应此标头会自动在您的浏览器中打开“另存为...”对话框,或根据您的浏览器设置立即开始下载到您的“下载”文件夹。

还可以考虑使用 servlet 而不是 JSP,如下所示: 导入java.io.File; 导入 java.io.FileInputStream; 导入 java.io.FileOutputStream; 导入 java.io.IOException; 导入 java.io.OutputStream; 导入 javax.servlet.ServletException; 导入 javax.servlet.http.HttpServlet; 导入 javax.servlet.http.HttpServletRequest; 导入 javax.servlet.http.HttpServletResponse;

public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File tempFile = File.createTempFile(getClass().getName(), ".xls");
        try {
            FileOutputStream fos = new FileOutputStream(tempFile);
            try {
                generateExcel(fos);
            } finally {
                fos.close();
            }

            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Length", String.valueOf(tempFile.length()));
            response.addHeader("Content-Disposition", String.format("attachment; filename=%s", tempFile.getName()));

            OutputStream outputStream = response.getOutputStream();
            FileInputStream fis = new FileInputStream(tempFile);
            try {
                int n = 0;
                byte[] buffer = new byte[1024];
                while ((n = fis.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, n);
                }
                outputStream.flush();
            } finally {
                fis.close();
            }
        } finally {
            tempFile.delete();
        }
    }

    private void generateExcel(OutputStream outputStream) throws IOException {
        // TODO This is stub. Place you excel generation code here
        outputStream.write("Hellol, world!".getBytes());
    }
}

更新 您无法使用 jQuery.ajax 函数以我描述的方式下载文件。我通常使用隐藏的 iframe:

$('#excel').click(function(){
    var fromdate = $('#fromdate').val();
    var todate = $('#todate').val();
    if(fromdate && todate) {
        var url = 'excel?fromdate=' + fromdate + '&todate=' + todate;
        $('#download-frame').attr('src', url);
    }
});

包含在您的页面标记中:

<iframe id="download-frame" src="" width="1" height="1" style="display: none"></iframe>

【讨论】:

  • 非常感谢您的宝贵建议,但文件大小和文件名应该写什么
  • fileSize 应该是 Excel 文件流的实际长度。您可以先在临时流中不直接导出到输出流 nut,例如 FileOutputStream 或 ByteArrayOutputStream。正如我之前所说,它不是强制标头,但告诉响应的长度是一个好习惯。
  • 我按照你的指示做了,但是这个 url 不支持获取 http 方法
  • 文件名由您决定。它可能取决于用户请求参数,例如,我的意思是 fromdate 和 todate。扩展名应为“.xls”(或 .xlsx),具体取决于生成文件的格式和相应的 mime 类型。
  • "get is not supported by this url" 谢谢,我修复了代码。您应该只覆盖 doGet() 方法而不是 service()。
【解决方案2】:

在浏览器中获取保存对话框以保存 java 中的下载文件:

不要使用 'onclick()' 函数,只需使用 href=""。

<script type="text/javascript" charset="utf-8">
var contextPath = "<%=request.getContextPath()%>";
</script>

var downloadUrl=contextPath+"/web/cms/downloadDocument.html?docId=" +docId;

<a> href='"+downloadUrl+"'>Download <a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多