HLJ 发布于
2022-09-05 08:26:25

JavaScript代码将多为数组导出到csv文件

<html>  
<head>  
<title> Download CSV file </title>  
</head>  
  
<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";  
    });  
   
    //display the created CSV data on the web browser   
    document.write(csv);  
  
     
    var hiddenElement = document.createElement('a');  
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);  
    hiddenElement.target = '_blank';  
      
    //provide the name for the CSV file to be downloaded  
    hiddenElement.download = 'Famous Personalities.csv';  
    hiddenElement.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>  
文章来源:https://www.javatpoint.com/javascript-create-and-download-csv-file
最后生成于 2022-10-07 22:28:03