如何使用Ajax请求创建和下载Excel文件 [英] How to create and Download Excel File by using Ajax request

查看:544
本文介绍了如何使用Ajax请求创建和下载Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户按下我网页上的公式按钮,我想创建一个Excel文件.我的第一个解决方案工作正常.用户按下按钮,服务器端的Java代码创建文件,并且在执行Java代码后,Web浏览器打开一个对话框,该对话框要求用户显示还是保存excel文件.

I want to create an Excel File, if the user pressed a formular button on my webpage. My first solution works fine. The User pressed the button, the serverside java code creates the file and after the java code was executed the webbrowser open a dialog, which aks the user whether to show or to save the excel file.

但是我从客户那里得到了一些新的要求.如果用户按下公式按钮,则必须在执行服务器端Java代码的同时显示动画gif图像,并且如果服务器端Java代码完成,则必须立即消失该动画gif.

But I get some new requirements from my customer. If the user pressed the formular button, it is necessary to show a animated gif image while the server side java code was executed and the animated gif must be disapeared immediately, if the server side java code was finished.

这是Struts2提交按钮,如果按下该按钮,它将启动HTTP请求:

This is the Struts2 submit Button, which starts the HTTP Request, if the button was pressed:

<s:submit value="show Data" onclick="myJsFunction(); return false;" />

这是客户端代码,它创建HTTP请求并将其发送到我的Struts2 Actionclass:

This is the client code, which creates and sends the HTTP Request to my Struts2 Actionclass:

function myJsFunction(){
     $.ajax({
              type: "POST",
              dataType: 'binary',
              url: "myActionClass.action",
              data: {//some necessary input values},                         
              success: function(data){                                   
                          console.log(data);
                          // js code to disappeared the animated gif image                          
                       }
      });               
 }

这是Java代码,用于创建Binarycode:

This is the Java code, which create the Binarycode:

private void returnExcelFileAsStream(final String filename) throws IOException {
    final InputStream is = new FileInputStream(filename);
    OutputStream os = null;
    try {
        response.setContentType("application/pdf");         
        response.setHeader("Cache-Control", "maxage=3600");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");         
        os = response.getOutputStream();
        int len;
        byte buf[] = new byte[1024];
        while ((len = is.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        is.close();
        os.close();
     }
     catch(Exception e){
         // some exeception handling
     }
}

这是Struts2执行方法,称为方法returnExcelFileAsStream.

This is the Struts2 execute method, which called the method returnExcelFileAsStream.

public String execute(){

    // some Java code
    returnExcelFileAsStream("MyExcelFile.xlsx")

    return null;
}

这是我的struts.xml文件:

This is my struts.xml file:

<action name="myActionClass" class="myPackage.myActionClass">
        <result name="input" type="redirectAction">/WEB-INF/base/jsp/myJspPage.jsp</result>
</action>

现在有一个问题,网络浏览器没有打开用户对话框,该对话框要求用户显示或保存文件.使用firebug时,我在HTTP响应中看到了一些神秘的字符.我怎么解决这个问题?

Now a have the problem, that the webbrowser doesn´t open a user dialog, which asked the user to show or to save the file. With firebug I see some cryptical characters in the HTTP Response. How can I solve this problem?

推荐答案

我是这样做的.

操作:

public String export() throws Exception {

HttpServletResponse response = ServletActionContext.getResponse();

List<FrontProjectList> dataList = projectApplyBaseService

.query_ProjectApply3(pqc, 0, projectApplyBaseService

.count_queryTotalProject_consumption(pqc) + 1);

HSSFWorkbook workbook = exportExcel(dataList);

ByteArrayOutputStream output = new ByteArrayOutputStream();

workbook.write(output);

byte[] ba = output.toByteArray();

excelFile = new ByteArrayInputStream(ba);

output.flush();

output.close();

return "excel";
}

Struts.xml

Struts.xml

            <param name="contentType">application/vnd.ms-excel</param>  

            <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>  

            <param name="bufferSize">1024</param>

            <param name="inputName">excelFile</param>  

        </result>  

这篇关于如何使用Ajax请求创建和下载Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆