Javascript: Export HTML Table to Excel With Custom File Name

Web browser wars hurt developers’ hearts. It is mostly about CSS, sometimes about JavaScript, HTML etc…

Thus I know how it feels when you expect something to get done easily appears a lot more harder than you expected.

Code below is tested only with Chrome (24+). It is making these processes:

  • Gets the HTML code of your table inside your div element.
  • Replaces the spaces in the code with correct syntax for Excel (otherwise spaces will be removed in your Excel sheet).
  • Generates a specific file name (for minutes) in order to avoid overriding old files and to supply archiving by date values.
  • And lastly and most importantly, saving the file with a custom file name.

Here’s my combination of codes (from different SO questions or tutorials) if you want to save HTML table to client computer using JavaScript code.

$(document).ready(function() {
	$("#btnExport").click(function(e) {
		//getting values of current time for generating the file name
		var dt = new Date();
		var day = dt.getDate();
		var month = dt.getMonth() + 1;
		var year = dt.getFullYear();
		var hour = dt.getHours();
		var mins = dt.getMinutes();
		var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
		//creating a temporary HTML link element (they support setting file names)
		var a = document.createElement('a');
		//getting data from our div that contains the HTML table
		var data_type = 'data:application/vnd.ms-excel';
		var table_div = document.getElementById('dvData');
		var table_html = table_div.outerHTML.replace(/ /g, '%20');
		a.href = data_type + ', ' + table_html;
		//setting the file name
		a.download = 'exported_table_' + postfix + '.xls';
		//triggering the function
		a.click();
		//just in case, prevent default behaviour
		e.preventDefault();
	});
});
  • Anibal

    Excelent, thanks a lot works great

    • http://www.kubilayerdogan.net/ Kubilay

      You’re welcome.

  • rajesh

    Hi Friend,

    I have try this code. Please let me know where this file stored?? I can’t to able see this file.

    • http://www.kubilayerdogan.net/ Kubilay

      Hello rajesh,

      This code is a JavaScript function. Make sure you have an input or button element in your page with “btnExport” id.

      When you hit that button, this code will execute and a “Save File” dialog will pop-up.

      Check this fiddle, it will help you: http://jsfiddle.net/kublaios/8ZQN4/1/

      • Adi

        That fiddle displays an html table correctly in the div, but the ‘Click for save’ button only works in Chrome 30 (not in IE10 or Firefox 24).
        Anyone know what the solution is?

  • rajesh

    this code execute successfully. But I can’t see the excel file.

  • rajesh

    please tell me??

  • Rajesh

    I have use this http://jsfiddle.net/kublaios/8ZQN4/1/

    but this code chrome browser only executed. Mozilla, IE not working. Please I need minimum 3 browsers working code.

    • http://www.kubilayerdogan.net/ Kubilay

      I have mentioned that I only tested in Chrome. You need to look other websites for browser compabilitied code.

      If you must supply for all browsers, you should look libraries or components. For example take a look at this: http://www.datatables.net/extras/tabletools/

    • Sohail

      Hi,

      replace
      var a = document.createElement(‘a’);
      with
      var a = document.createElement(‘a’);

      and add this line under body tag

      then check it will work on mozilla also. :)

  • Rajesh

    Thank u buddy… I’ve finished export Excel & PDF.

  • Jayati

    i m not able to save all columns..

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      What kind of output do you get? Or how many columns does your table have? I’ve never tried with large amount of columns but I don’t see any reason not to work in such situation.

      Did you make sure that the HTML of your table is %100 correct? To validate your table’s HTML code, use this online tool and see if indents of opening and closing tags match: http://jsbeautifier.org/

      If you need further help, you need to clarify the issue with details.

      Regards,

      • http://www.aa.com Ahad

        Excelent, thanks a lot works great

  • narasimha

    Hi,
    how do i remove paging before going to export to excel.

  • Brian

    I can’t even get your example to work for me. The code works on jsfiddle, but if I make the same example on my server, the button does nothing.

  • Brian

    I can’t get the example to work. It works on jsfiddle, but if I make the same example on my server, it does not work. The button does nothing.

    • http://www.kubilayerdogan.net/ Kubilay

      If it works on jsFiddle, that means the code is correct. You should check your source file and make sure no tag errors exist. To validate, use this link: http://jsbeautifier.org/

      Also, try to change orders of table and script code in the page.

  • Sandeep

    Hi, i tried the JsFiddle code in mozilla, but it doesn’t work
    Can you please help

  • Sandeep

    i used this code http://jsfiddle.net/insin/cmewv/
    But it is giving some random filename
    how to get a specific filename
    Please help

    • http://www.kubilayerdogan.net/ Kubilay

      Hi Sandeep,

      I don’t know where did you get this code but at least it works in Firefox, this was the problem in your case I guess.

      However, you might need to ask for help in the page you found the code. As I mentioned in this topic, I’ve tested in Google Chrome only, can’t say about other browsers.

      If you ask my advice, you should try something that is told to be working in other browsers, check the link in this comment: http://www.kubilayerdogan.net/?p=218#comment-2081

      Hope this helps,
      Regards.

  • Utha

    i have problem in here.i save the script as excel.js, so in the html i put this code “”. when i run this program, there is a warning message window, it contains
    Error: ‘$’ is undefined
    i hope u can solve the problem, thanks and sry for my bad english

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      Did you include jQuery in the head section of your HTML page? It appears to be a jQuery problem, it either can’t find the jQuery library or can’t find the element with the id “btnExport”.

      Regards.

  • Philip

    Would it be possible for you to post a sample html file which works with this? I’d very much appreciate it.

  • Prabakaran

    hai ,
    i need to export html table to excel.but in my html table it consists of image(ie.., image column consists of small images)

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      I don’t think it’s possible with this solution. You should check out commerical products or exporting ways to PDF files.

      Regards,
      Kubilay

      • Prabakaran

        thanks for your reply.i will give a try..

  • Raghu

    Hi,

    The Code was very helpful to me. As you said , its not working in mozilla.I have completed almost all just downloading html table as excel file is pending, hereafter i could not move to datatables . Could you please suggest me any other solution?

  • Bhagirath

    Hi…i found a solution which works on firefox as well as chrome….check it out….
    http://jsfiddle.net/terryyounghk/KPEGU/

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      Thank you for the snippet. It seems that it’s saving as CSV, it makes sense. I think that it’ll help lots of friends so I’ll attach it to the topic when I get a chance.

      Regards.

  • sai

    I have a problem. I have an excel template in server and i need to paste the HTML table on the template.How do i access the template present in the server with the above code provided by you.I have to url for the template .I have the code for IE which doesnt work in Chrome.

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      Instead of trying to read an Excel template, you can create an invisible table that matches your template and try to use it.

      I think it should be kept in the client-size, otherwise it gets too complicated.

      Regards,
      Kubilay

  • sreehari

    please let me know how can i export data to an excelsheet template which is server location.

  • Aaron

    So I got the snippet to work for a small table, but it crashes when the table becomes extremely big. It crashes on the a.click(); line. I believe this is because the href has too many characters, but I don’t know for sure. Is there a limit to the number of characters or table size to make this work?

    • http://www.kubilayerdogan.net/ Kubilay

      Hi,

      I haven’t seen any limit so far, however I can’t say I’ve tried either. It might be related to the data you include in your table, perhaps it’s not pure text.

      I think you can explode the table to subtables when you begin to export and implode after the export of all parts.

      Regards,
      Kubilay

  • herold park

    Thanks lots.
    it’s right solution that found.

  • ozgur

    Teşekkürler, çok işe yaradi

  • RockMan

    Thanks so much .. After lot of searching I found the key code ‘%20′ for space to write into excel using javascript.

  • http://facebook.com/ashinga48 ashinga

    thanks for the script man.. its works damn good…

  • http://www.sistemoptima.com Kaan K

    Harika dostum, çok zaman kazandım.. :) kolay gelsin..

  • Pedro Cova

    My special characters like “ã” don’t appear like should! Can you tell me why?

  • R Buurman

    Very smart solution, thanks!

  • Campanilla

    Hi!
    Thank you for sharing this code! I’m new at programming with java and it’s been really useful, but I still have some problems… I’m trying to export different html tables in the same Excel. I want them to be in different sheets. With this code I get one table in one excel and the name of the sheet is the same as the Excel. Do you know how could I do it?

  • teoman

    great tool thanks for sharing..

  • Rajiv

    Wow! Thanks for sharing man!!!

  • Naresh

    HI ,is there any possibility to remove all anchors in the output excel file ???

  • Sam

    Thanks for this.. works well & very helpful.

  • Vasilis

    Hello guys, I used this code to my website and it was working perfect… Do you know what happened and it stopped working? When I click on it instead of getting the xls file with the name etc I get a simple file named download which has the html table in it.. :(
    Please help me!

  • Jamie

    I’ve had the same issue.. It was working fine and now I get a file with no extension named ‘download’..

  • Vasilis

    Hello Jamie,

    I’ve been having the same issue of late, and the problem comes from a recent Chrome update (chromium actually, so it might affect other Chromium-based browsers) which has been reported and is currently being fixed (https://code.google.com/p/chromium/issues/detail?id=373182).

  • umut

    Merhaba kubilay peki exceldeki yazdırma boyutunu nasıl a4′e sığdırabiliriz. Epeydir bunu çözmeye çalışıyorum.

    • http://www.kubilayerdogan.net/ Kubilay

      Merhaba,

      Biraz araştırdığımda ben de pek somut bir şey bulamadım fakat bir düzenleme yapılacaksa “var data_type = ‘data:application/vnd.ms-excel’” satırında olma ihtimali yüksek. Excel’e buradan header gönderilebilirse belki parametreler ile sayfa boyutu ayarlanabilir.

      Doğrudan çözüm içermese de aşağıdaki bağlantıda bu export işlemi hakkında farklı kodlar var, belki faydası dokunur: https://gist.github.com/insin/1031969

      İyi çalışmalar,
      Kubilay

  • matcafe

    Nice and elegant solution! Saved my day!

  • Mario

    A real lifesaver! Thank you for this nifty piece of work!