Why does exporting HTML table data to Excel using JavaScript work in Firefox but fail in Chrome?

I have an HTML table in a Velocity template and want to export its data to Excel using JavaScript or jQuery compatible with all browsers. My current script:

function ExportToExcel(mytblId){
   var htmltable = document.getElementById('my-table-id');
   var html = htmltable.outerHTML;
   window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}

This triggers a proper Excel dialog in Firefox, but in Chrome, clicking the button downloads a file without an .xls extension and no prompt appears. There are no console errors.

Why does this happen in Chrome, and how can I fix the javascript export to excel functionality to work consistently?

Chrome and Firefox handle data URLs differently. Firefox’s window.open() with a data: URL triggers the Open with Excel dialog nicely.

But Chrome treats it as a direct download with no filename or extension, so you just get a raw file without the .xls extension or prompt.

To fix this, you need to explicitly create a downloadable file with the right name and MIME type instead of just opening a data URL.

Using an anchor tag with a download attribute and a Blob usually does the trick across browsers.

Instead of window.open(), try creating a Blob from your table’s HTML, then create an <a> element with a download attribute and trigger a click on it.

Like this:

function ExportToExcel(mytblId) {
  var htmltable = document.getElementById(mytblId);
  var html = htmltable.outerHTML;
  var blob = new Blob([html], { type: 'application/vnd.ms-excel' });
  var url = URL.createObjectURL(blob);

  var a = document.createElement('a');
  a.href = url;
  a.download = 'table-export.xls';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

This approach works well on Chrome, Firefox, and Edge, and it ensures you get a proper .xls file with the right prompt.

The quick HTML table to Excel trick is somewhat hacky and inconsistent across browsers, especially Chrome.

Also, Excel might complain about the file format since the content is HTML but the extension is .xls.

For a more robust solution, consider libraries like SheetJS (xlsx) which can convert tables or JSON data to real Excel files programmatically.

It’s a bit more setup but gives you full control and cross-browser compatibility without relying on browser quirks.