javascript 将 Html 表格导出到 Excel - 所有浏览器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18925538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:42:18  来源:igfitidea点击:

Export Html Table to Excel - All Browsers

javascriptjqueryhtmljspexport-to-excel

提问by Trevor

I am having trouble exporting my html table to Excel here is what I have tried.

我在这里尝试将我的 html 表导出到 Excel 时遇到问题。

window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('#myTableDiv').html()));

Works amazingly on chrome, but does not work on Internet explorer; Just goes to a new tab with the data in the url (tried on IE10). So I tried checking for IE and then using the ActiveXObject method for IE browsers.

在 chrome 上效果惊人,但在 Internet Explorer 上不起作用;只需转到带有 url 数据的新选项卡(在 IE10 上尝试过)。所以我尝试检查IE,然后使用IE浏览器的ActiveXObject方法。

var objExcel = new ActiveXObject ("Excel.Application");

But It gave me errors when creating the object and I have Excel 2013 on my computer. This method does not seem very reliable.

但是在创建对象时它给了我错误,我的计算机上有 Excel 2013。这种方法似乎不太可靠。

So now I am on to attempting it with a server side language (JSP).

所以现在我开始尝试使用服务器端语言 (JSP)。

Here is my current attempt.

这是我目前的尝试。

$('.toExcel').click(function(){
    $.post('controllers/excel.jsp?tableHTML=' + encodeURIComponent($('#myTableDiv').html()), function(data) {   

    });
});

And my JSP

还有我的 JSP

<!DOCTYPE html>
<%@ page import="java.io.PrintWriter" %>  
<%@ page contentType="application/excel" language="java" %>  
<%    
   response.reset();  
   response.setHeader("Content-Type", "application/vnd.ms-excel");
   response.setHeader("Content-Disposition", "attachment;filename=\"report.xls\"");  
   PrintWriter op = response.getWriter();  
   String CSV = request.getParameter("tableHTML");   
   op.write(CSV);  
%>  

I know there are at least a few issues with this.

我知道这至少存在一些问题。

  1. When posting to the url there is no download prompt.
  2. Only so much html can fit as a parameter
  1. 发布到 url 时没有下载提示。
  2. 只有这么多 html 可以作为参数

When I navigate to the request url in chrome it downloads the file. When I navigate to the request url in IE 10 I get the following error:

当我导航到 chrome 中的请求 url 时,它会下载文件。当我导航到 IE 10 中的请求 url 时,出现以下错误:

  HTML1527: DOCTYPE expected. The shortest valid doctype is "<!DOCTYPE html>". 
  excel.jsp, line 1 character 1

Can anyone help me with a reliable solution that will work for all browsers?

任何人都可以帮助我提供适用于所有浏览器的可靠解决方案吗?

采纳答案by Trevor

One Solution using JSPand JavaScript

使用JSP和的一种解决方案JavaScript

  1. Export to Excel JS function. Pass in table ID

    function exportToExcel(intable){
        intable = document.getElementById(intable);
        this.table = intable.cloneNode(true);
        var cform = document.createElement("form");
        cform.style.display = "none";
        cform.setAttribute("method","POST");
        cform.setAttribute("action","exporttoexcel.jsp");
        cform.setAttribute("name","ExcelForm");
        cform.setAttribute("id","ExcelForm");
        cform.setAttribute("enctype","MULTIPART/FORM-DATA");
        cform.encoding="multipart/form-data";
        var ta = document.createElement("textarea");
        ta.name = "ExcelTable";
        var tabletext = this.table.outerHTML;
        ta.defaultValue = tabletext;
        ta.value = tabletext;
        cform.appendChild(ta);
        intable.parentNode.appendChild(cform);
        cform.submit();
        //clean up
        ta.defaultValue = null;
        ta = null;
        tabletext = null;
        this.table = null;
    }
    
  2. And the codefor exporttoexcel.jsp

    <%@ page import="java.util.*"%>
    <%@ page import="java.io.*" %> 
    <%@ page import="org.apache.commons.fileupload.*" %>
    <%@ page import="org.apache.commons.fileupload.disk.*" %>
    <%@ page import="org.apache.commons.fileupload.servlet.*" %>
    <%
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","attachment; filename=" + "MyReport.xls" );
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Iterator pit = null;
    DiskFileItem dfi = null;
    String line = ""; 
    if(isMultipart){
        //      Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
    
        //      Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
    
        //      Parse the request
        File f = null;
        dfi = null;
        List items = null;
        items = upload.parseRequest(request);
        pit = items.iterator();
    
     }
     if(isMultipart){
        while(pit.hasNext()){
            dfi = (DiskFileItem)pit.next();
            String name = dfi.getFieldName();
            if (name.equalsIgnoreCase("ExcelTable")){
                InputStream is = dfi.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                while((line = br.readLine()) != null){
                    out.println(line);
                }                                   
            }
         }
      }else{
        Enumeration params = request.getParameterNames();
        while(params.hasMoreElements()){
            String par = (String)params.nextElement();
            out.println(par+"<br>");
            out.println(request.getParameter(par));
        }
      }
    %>
    
  1. 导出到 Excel JS 功能。 Pass in table ID

    function exportToExcel(intable){
        intable = document.getElementById(intable);
        this.table = intable.cloneNode(true);
        var cform = document.createElement("form");
        cform.style.display = "none";
        cform.setAttribute("method","POST");
        cform.setAttribute("action","exporttoexcel.jsp");
        cform.setAttribute("name","ExcelForm");
        cform.setAttribute("id","ExcelForm");
        cform.setAttribute("enctype","MULTIPART/FORM-DATA");
        cform.encoding="multipart/form-data";
        var ta = document.createElement("textarea");
        ta.name = "ExcelTable";
        var tabletext = this.table.outerHTML;
        ta.defaultValue = tabletext;
        ta.value = tabletext;
        cform.appendChild(ta);
        intable.parentNode.appendChild(cform);
        cform.submit();
        //clean up
        ta.defaultValue = null;
        ta = null;
        tabletext = null;
        this.table = null;
    }
    
  2. code对于exporttoexcel.jsp

    <%@ page import="java.util.*"%>
    <%@ page import="java.io.*" %> 
    <%@ page import="org.apache.commons.fileupload.*" %>
    <%@ page import="org.apache.commons.fileupload.disk.*" %>
    <%@ page import="org.apache.commons.fileupload.servlet.*" %>
    <%
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","attachment; filename=" + "MyReport.xls" );
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Iterator pit = null;
    DiskFileItem dfi = null;
    String line = ""; 
    if(isMultipart){
        //      Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
    
        //      Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
    
        //      Parse the request
        File f = null;
        dfi = null;
        List items = null;
        items = upload.parseRequest(request);
        pit = items.iterator();
    
     }
     if(isMultipart){
        while(pit.hasNext()){
            dfi = (DiskFileItem)pit.next();
            String name = dfi.getFieldName();
            if (name.equalsIgnoreCase("ExcelTable")){
                InputStream is = dfi.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                while((line = br.readLine()) != null){
                    out.println(line);
                }                                   
            }
         }
      }else{
        Enumeration params = request.getParameterNames();
        while(params.hasMoreElements()){
            String par = (String)params.nextElement();
            out.println(par+"<br>");
            out.println(request.getParameter(par));
        }
      }
    %>
    

回答by Aditya Lodha

I will tell you a simple solution

我会告诉你一个简单的解决方案

add one button in the page where table is

在table所在页面添加一个按钮

<button class="btn btn-success">Export Data to Excel</button>

now add the below given scripts to the same page

现在将下面给定的脚本添加到同一页面

<script src="js/jquery.table2excel.js"></script>
 <script>
      $(function() {
        $("button").click(function() {
           $("#tableID").table2excel({
             exclude: ".noExl",
             name: "Excel Document Name"
           });
        });
     });
</script>

Do not forget to download jquery.table2excel.js and add this to js folder

不要忘记下载 jquery.table2excel.js 并将其添加到 js 文件夹