将html表导出到csv

sam*_*sam 42 javascript jquery html-table node.js export-to-csv

我想在我的网站上添加csv下载选项的功能.它应该将网站中的html表转换为csv内容并使其可下载.我一直在互联网上搜索一个很好的插件,并找到了一些像http://www.dev-skills.com/export-html-table-to-csv-file/ 这样的用途,但它使用php脚本来做下载部分.我想知道是否有一个纯javascript库可用于使用服务器端软件如node.js而不使用php?

mel*_*cia 36

使用just jQuery和vanilla Javascript:

出口到HTML表-AS-CSV文件 - 使用 - jQuery的

将此代码放入要在以下table2CSV部分加载的脚本中:

 $(document).ready(function () {
    $('table').each(function () {
        var $table = $(this);

        var $button = $("<button type='button'>");
        $button.text("Export to spreadsheet");
        $button.insertAfter($table);

        $button.click(function () {
            var csv = $table.table2CSV({
                delivery: 'value'
            });
            window.location.href = 'data:text/csv;charset=UTF-8,' 
            + encodeURIComponent(csv);
        });
    });
})
Run Code Online (Sandbox Code Playgroud)

笔记:

需要jQuerytable2CSV:在上面的脚本之前向两个库添加脚本引用.

head选择作为一个例子,可以调整,以满足您的需求.

它仅适用于完全table支持的浏览器:Firefox,Chrome和Opera,而不是IE,它只支持Data URI将二进制图像数据嵌入到页面中.

要获得完全的浏览器兼容性,您必须使用略微不同的方法,该方法需要服务器端脚本才能Data URIs使用CSV.


Bud*_*tne 10

http://jordiburgos.com/post/2014/excellentexport-javascript-export-to-excel-csv.html上有一个非常简单的免费开源解决方案

首先从https://github.com/jmaister/excellentexport/releases/tag/v1.4下载javascript文件和示例文件

html页面如下所示.

确保javascript文件位于同一文件夹中,或相应地更改html文件中脚本的路径.

<html>
<head>
    <title>Export to excel test</title>
    <script src="excellentexport.js"></script>
    <style>
        table, tr, td {
            border: 1px black solid;
        }
    </style>
</head>
<body>
    <h1>ExcellentExport.js</h1>

    Check on <a href="http://jordiburgos.com">jordiburgos.com</a> and  <a href="https://github.com/jmaister/excellentexport">GitHub</a>.

    <h3>Test page</h3>

    <br/>

    <a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
    <br/>

    <a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>
    <br/>

    <table id="datatable">
        <tr>
            <th>Column 1</th>
            <th>Column "cool" 2</th>
            <th>Column 3</th>
        </tr>
        <tr>
            <td>100,111</td>
            <td>200</td>
            <td>300</td>
        </tr>
        <tr>
            <td>400</td>
            <td>500</td>
            <td>600</td>
        </tr>
        <tr>
            <td>Text</td>
            <td>More text</td>
            <td>Text with
                new line</td>
        </tr>
    </table>

</body>
Run Code Online (Sandbox Code Playgroud)

这很容易使用,因为我已经尝试了大多数其他方法.


Ita*_*tto 8

您不需要服务器端的PHP脚本.仅在客户端执行此操作,在接受数据URI的浏览器中:

data:application/csv;charset=utf-8,content_encoded_as_url
Run Code Online (Sandbox Code Playgroud)

数据URI将类似于:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式调用此URI:

  • 运用 window.open
  • 或设置 window.location
  • 或者通过锚的href
  • 通过添加下载属性,它将在chrome中工作,仍然需要在IE中进行测试.

要进行测试,只需复制上面的URI并粘贴到浏览器地址栏中即可.或者在HTML页面中测试下面的锚点:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>
Run Code Online (Sandbox Code Playgroud)

要创建内容,从表中获取值,您可以使用MelanciaUK提到的table2CSV并执行:

var csv = $table.table2CSV({delivery:'value'});
window.location.href = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);
Run Code Online (Sandbox Code Playgroud)


Cal*_*mah 6

应该可以在每种现代浏览器上运行,并且没有jQuery或任何依赖关系,这是我的实现:

// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id) {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote (see /sf/ask/1246595801/)
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(';'));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
Run Code Online (Sandbox Code Playgroud)

然后添加您的下载按钮/链接:

<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>
Run Code Online (Sandbox Code Playgroud)

CSV文件具有时间限制,并且与默认Excel格式兼容。

  • 出色的!从 csv.push(row.join(';')); 更改一行后 到 csv.push(row.join(',')); ,它对我有用。 (5认同)
  • 我必须将 `var rows = document.querySelectorAll('table#' + table_id + ' tr');` 更改为 `var rows = document.querySelectorAll('#' + table_id + ' tr');` 才能使其正常工作,但现在一切都很好 (2认同)

ran*_*umo 6

现代解决方案

这里提出的大多数解决方案都会破坏 td 元素中的嵌套表或其他元素。我经常在表格中使用其他元素,但只想导出最上面的表格。我从 Calumah 获取了一些在这里找到的代码,并添加了一些现代的普通 ES6 JS。

使用textContent是比innerText 更好的解决方案,因为innerText 将返回td 元素内的任何HTML。但是,即使 textContent 也会返回嵌套元素中的文本。更好的解决方案是在 td 上使用自定义数据属性,并从那里提取 CSV 的值。

快乐编码!

function downloadAsCSV(tableEle, separator = ','){
    let csvRows = []
    //only get direct children of the table in question (thead, tbody)
    Array.from(tableEle.children).forEach(function(node){
        //using scope to only get direct tr of node
        node.querySelectorAll(':scope > tr').forEach(function(tr){
            let csvLine = []
            //again scope to only get direct children
            tr.querySelectorAll(':scope > td').forEach(function(td){
                //clone as to not remove anything from original
                let copytd = td.cloneNode(true)
                let data
                if(copytd.dataset.val) data = copytd.dataset.val.replace(/(\r\n|\n|\r)/gm, '')
                else {
                    Array.from(copytd.children).forEach(function(remove){
                        //remove nested elements before getting text
                        remove.parentNode.removeChild(remove)   
                    })
                    data = copytd.textContent.replace(/(\r\n|\n|\r)/gm, '')
                }
                data = data.replace(/(\s\s)/gm, ' ').replace(/"/g, '""')
                csvLine.push('"'+data+'"')
            })
            csvRows.push(csvLine.join(separator))
        })
    })
    var a = document.createElement("a")
    a.style = "display: none; visibility: hidden" //safari needs visibility hidden
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvRows.join('\n'))
    a.download = 'testfile.csv'
    document.body.appendChild(a)
    a.click()
    a.remove()
}
Run Code Online (Sandbox Code Playgroud)

编辑:cloneNode()更新为cloneNode(true)以获取内部信息


dab*_*eng 5

(1)这是针对这个问题的原生javascript解决方案。它适用于大多数现代浏览器。

function export2csv() {
  let data = "";
  const tableData = [];
  const rows = document.querySelectorAll("table tr");
  for (const row of rows) {
    const rowData = [];
    for (const [index, column] of row.querySelectorAll("th, td").entries()) {
      // To retain the commas in the "Description" column, we can enclose those fields in quotation marks.
      if ((index + 1) % 3 === 0) {
        rowData.push('"' + column.innerText + '"');
      } else {
        rowData.push(column.innerText);
      }
    }
    tableData.push(rowData.join(","));
  }
  data += tableData.join("\n");
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
  a.setAttribute("download", "data.csv");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
Run Code Online (Sandbox Code Playgroud)
table {
  border-collapse: collapse;
}

td, th {
  border: 1px solid #aaa;
  padding: 0.5rem;
  text-align: left;
}

td {
  font-size: 0.875rem;
}

.btn-group {
  padding: 1rem 0;
}

button {
  background-color: #fff;
  border: 1px solid #000;
  margin-top: 0.5rem;
  border-radius: 3px;
  padding: 0.5rem 1rem;
  font-size: 1rem;
}

button:hover {
  cursor: pointer;
  background-color: #000;
  color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Author</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>jQuery</td>
      <td>John Resig</td>
      <td>The Write Less, Do More, JavaScript Library.</td>
    </tr>
    <tr>
      <td>React</td>
      <td>Jordan Walke</td>
      <td>React makes it painless to create interactive UIs.</td>
    </tr>
    <tr>
      <td>Vue.js</td>
      <td>Yuxi You</td>
      <td>The Progressive JavaScript Framework.</td>
    </tr>
  </tbody>
</table>

<div class="btn-group">
  <button onclick="export2csv()">csv</button>
</div>
Run Code Online (Sandbox Code Playgroud)

(2) 如果你想要一个纯javascript库,FileSaver.js可以帮你保存触发文件下载的代码片段。此外,FileSaver.js 将不负责构建导出内容。您必须以您想要的格式自行构建内容。