Trevor
Trevor

Reputation: 16116

Export Html Table to Excel - All Browsers

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

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.

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.

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

Here is my current attempt.

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

    });
});

And my 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

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:

  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?

Upvotes: 1

Views: 13019

Answers (2)

Aditya Lodha
Aditya Lodha

Reputation: 106

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

Upvotes: 2

Trevor
Trevor

Reputation: 16116

One Solution using JSP and 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 code for 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));
        }
      }
    %>
    

Upvotes: 0

Related Questions