A button to download the CSV file on browser by javascript

Post Reply
tthlan
Quản trị viên
Posts: 76
Joined: Tue Aug 23, 2016 8:13 am

A button to download the CSV file on browser by javascript

Post by tthlan »

Code: Select all

<html>
<body>

<script>  
//create CSV file data in an array  
var csvFileData = [  
   ['Alan Walker', 'Singer'],  
   ['Cristiano Ronaldo', 'Footballer'],  
   ['Saina Nehwal', 'Badminton Player'],  
   ['Arijit Singh', 'Singer'],  
   ['Terence Lewis', 'Dancer']  
];  
    
//create a user-defined function to download CSV file   
function download_csv_file() {  
  
    //define the heading for each row of the data  
    var csv = 'Name,Profession\n';  
      
    //merge the data with CSV  
    csvFileData.forEach(function(row) {  
            csv += row.join(',');  
            csv += "\n";  
    });     

    // Force download file
    var type = 'text/csv'; 
    const anchor = document.createElement('a');
    anchor.href = window.URL.createObjectURL(new Blob([csv], { type }));
    anchor.download = 'Famous Personalities.csv';
    anchor.click();
}  
</script>  
  
<body>  
<h3> Click the button to download the CSV file </h3>  
  
<!-- create an HTML button to download the CSV file on click -->  
<button onclick="download_csv_file()"> Download CSV </button>  
  
</body>
</html>
Post Reply