简体   繁体   English

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

[英]Export Html Table to Excel - All Browsers

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; 在chrome上效果惊人,但在Internet Explorer上不起作用; Just goes to a new tab with the data in the url (tried on IE10). 只需转到网址中包含数据的新标签页(在IE10上试用)。 So I tried checking for IE and then using the ActiveXObject method for IE browsers. 因此,我尝试检查IE,然后将ActiveXObject方法用于IE浏览器。

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

But It gave me errors when creating the object and I have Excel 2013 on my computer. 但这在创建对象时给了我错误,并且我的计算机上装有Excel 2013。 This method does not seem very reliable. 这种方法似乎不是很可靠。

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. 当发布到URL时,没有下载提示。
  2. Only so much html can fit as a parameter 只有那么多的html可以作为参数

When I navigate to the request url in chrome it downloads the file. 当我导航到Chrome中的请求网址时,它将下载文件。 When I navigate to the request url in IE 10 I get the following error: 当我导航到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? 谁能为我提供适用于所有浏览器的可靠解决方案?

I will tell you a simple solution 我会告诉你一个简单的解决方案

add one button in the page where table is 在表格所在的页面中添加一个按钮

<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文件夹

One Solution using JSP and JavaScript 一种使用JSPJavaScript解决方案

  1. Export to Excel JS function. 导出到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. And the code for exporttoexcel.jsp 以及exporttoexcel.jspcode

     <%@ 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)); } } %> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM