我有下表
<table>
<tr><th>Name</th><th>Age</th><th>Country</th></tr>
<tr><td>Geronimo</td><td>26</td><td>France</td></tr>
<tr><td>Natalia</td><td>19</td><td>Spain</td></tr>
<tr><td>Silvia</td><td>32</td><td>Russia</td></tr>
</table>
<br/>
<table>
<tr><th>Pet</th><th>Breed</th><th>Type</th></tr>
<tr><td>Roscoe</td><td>Pug</td><td>Dog</td></tr>
<tr><td>Polly</td><td>Parrot</td><td>Bird</td></tr>
<tr><td>Whiskers</td><td>Calico</td><td>Cat</td></tr>
</table>
<br/>
<table>
<tr><th>Pet</th><th>Breed</th><th>Type</th></tr>
<tr><td>Roscoe</td><td>Pug</td><td>Dog</td></tr>
<tr><td>Polly</td><td>Parrot</td><td>Bird</td></tr>
<tr><td>Whiskers</td><td>Calico</td><td>Cat</td></tr>
</table>
<button>Export HTML table to CSV file</button>
我有下面的JS代码
function download_csv(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;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, 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
download_csv(csv.join("\n"), filename);
}
document.querySelector("button").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
此代码将html表转换为要下载的csv文件。我想知道是否有可能以某种方式添加一些样式,以便在Excel中打开csv时会显示带有某些颜色的表格标题。
这是小提琴Fiddle
谢谢
答案 0 :(得分:1)
不幸的是,没有! CSV文件基本上是原始单元格数据,完全没有格式。
如果您想要一些样式,则需要学习以下格式之一。但这将更加复杂。