我正在尝试从html表下载csv文件。
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Country</th>
</tr>
<tr>
<td>John Doe</td>
<td>john@gmail.com</td>
<td>USA</td>
</tr>
<tr>
<td>Stephen Thomas</td>
<td>stephen@gmail.com</td>
<td>UK</td>
</tr>
<tr>
<td>Natly Oath</td>
<td>natly@gmail.com</td>
<td>France</td>
</tr>
</table>
<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>
<script>
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();// throwing error.
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
</script>
</body>
</html>
但在IE 11上收到错误 SCRIPT5:访问被拒绝。在downloadLink.click();
相同的代码在其他浏览器中工作,如chrome,mozilla firefox等。 非常感谢任何帮助。
代码ref: https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/?