How to change the file name when exporting data to Excel?

How to change the file name when exporting data to Excel?

<div id="example" class="k-content"> <button type="button"id="btnExport">Export to csv!</button> <div id="grid"></div> </div> <script> $("#btnExport").click(function (e) { var result = "data:application/vnd.ms-excel,"; window.open(result); e.preventDefault(); }); </script> 

When I click the export button, I get like download.xls. Is it possible to set the file name as data.xls? Can someone explain to me where I need to configure this?

thanks

+4
source share
4 answers

Here is an example demonstrating Exporting an HTML table to Excel with a custom file name: http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/

+6
source

I had the same problem, and since the new format (maybe not supported by each browser) <a download=""></a> , it worked fine for me. This directly uses HTML / Javascript without part of the PHP server, because using a submit form is too heavy for large data tables.

  • change <button> to <a>
  • no more than window.open()
  • using the basic behavior <a> (therefore, no more than e.preventDefault() ), but changing href to data:blabla and adding download="filename" :
 <div id="example" class="k-content"> <a href="#" id="btnExport" >Export to csv!</a> <div id="grid"></div> </div> <script> $("#btnExport").click(function (e) { var result = "data:application/vnd.ms-excel,"; this.href = result; this.download = "my-custom-filename.xls"; return true; }); </script> 
+2
source

You cannot do this using client-side JavaScript, you need to set the response header ...

.NET

 Response.AddHeader("Content-Disposition", "inline;filename=filename.xls") 

Or php

 $filename = 'somehting.xls'; header('Content-Disposition: attachment; filename="'.$filename.'"'); 
+1
source
 Response.AddHeader "Content-Disposition", "attachment; filename=C:\YOURFILENAME.xls;" 
+1
source

All Articles