如何将 html 表格数据导出为 .csv 文件?

问题描述 投票:0回答:9

我在网站上有一个 html 表格中的数据表,需要知道如何将该数据导出为 .csv 文件。

这将如何完成?

html parsing csv export export-to-csv
9个回答
28
投票

要将 html 导出到 csv,请尝试遵循此示例。 更多详细信息和示例请访问 作者网站

创建一个 html2csv.js 文件并将以下代码放入其中。

jQuery.fn.table2CSV = function(options) {
    var options = jQuery.extend({
        separator: ',',
        header: [],
        delivery: 'popup' // popup, value
    },
    options);

    var csvData = [];
    var headerArr = [];
    var el = this;

    //header
    var numCols = options.header.length;
    var tmpRow = []; // construct header avalible array

    if (numCols > 0) {
        for (var i = 0; i < numCols; i++) {
            tmpRow[tmpRow.length] = formatData(options.header[i]);
        }
    } else {
        $(el).filter(':visible').find('th').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
    }

    row2CSV(tmpRow);

    // actual data
    $(el).find('tr').each(function() {
        var tmpRow = [];
        $(this).filter(':visible').find('td').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
        row2CSV(tmpRow);
    });
    if (options.delivery == 'popup') {
        var mydata = csvData.join('\n');
        return popup(mydata);
    } else {
        var mydata = csvData.join('\n');
        return mydata;
    }

    function row2CSV(tmpRow) {
        var tmp = tmpRow.join('') // to remove any blank rows
        // alert(tmp);
        if (tmpRow.length > 0 && tmp != '') {
            var mystr = tmpRow.join(options.separator);
            csvData[csvData.length] = mystr;
        }
    }
    function formatData(input) {
        // replace " with “
        var regexp = new RegExp(/["]/g);
        var output = input.replace(regexp, "“");
        //HTML
        var regexp = new RegExp(/\<[^\<]+\>/g);
        var output = output.replace(regexp, "");
        if (output == "") return '';
        return '"' + output + '"';
    }
    function popup(data) {
        var generator = window.open('', 'csv', 'height=400,width=600');
        generator.document.write('<html><head><title>CSV</title>');
        generator.document.write('</head><body >');
        generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
        generator.document.write(data);
        generator.document.write('</textArea>');
        generator.document.write('</body></html>');
        generator.document.close();
        return true;
    }
};

将js文件包含到html页面中,如下所示:

<script type="text/javascript" src="jquery-1.3.2.js" ></script>

<script type="text/javascript" src="html2CSV.js" ></script>

表:

<table id="example1" border="1"  style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3">

    <tr>

        <th>Title</th>

        <th>Name</th>

        <th>Phone</th>

    </tr>

    <tr>

        <td>Mr.</td>

        <td>John</td>

        <td>07868785831</td>

    </tr>

    <tr>

        <td>Miss</td>

        <td><i>Linda</i></td>

        <td>0141-2244-5566</td>

    </tr>

    <tr>

        <td>Master</td>

        <td>Jack</td>

        <td>0142-1212-1234</td>

    </tr>

    <tr>

        <td>Mr.</td>

        <td>Bush</td>

        <td>911-911-911</td>

    </tr>

</table>

导出按钮:

<input value="Export as CSV 2" type="button" onclick="$('#example1').table2CSV({header:['prefix','Employee Name','Contact']})">

27
投票

我能够使用此处概述的答案:使用 jQuery 和 html 导出到 CSV 并添加修改以使其在 IE 中工作,以及评论中提到的另一个修改以从表中获取标题。

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td),tr:has(th)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row), $cols = $row.find('td,th');

            return $cols.map(function (j, col) {
                var $col = $(col), text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"',



        // Data URI
        csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        console.log(csv);

        if (window.navigator.msSaveBlob) { // IE 10+
            //alert('IE' + csv);
            window.navigator.msSaveOrOpenBlob(new Blob([csv], {type: "text/plain;charset=utf-8;"}), "csvname.csv")
        } 
        else {
            $(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); 
        }
}

// This must be a hyperlink
$("#xx").on('click', function (event) {

    exportTableToCSV.apply(this, [$('#projectSpreadsheet'), 'export.csv']);

    // IF CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});

我的链接看起来像这样...

<a href="#" id="xx" style="text-decoration:none;color:#000;background-color:#ddd;border:1px solid #ccc;padding:8px;">Export Table data into Excel</a>

JsFiddle:https://jsfiddle.net/mnsinger/65hqxygo/


5
投票

下面的解决方案可以做到。

$(function() {
  $("button").on('click', function() {
    var data = "";
    var tableData = [];
    var rows = $("table tr");
    rows.each(function(index, row) {
      var rowData = [];
      $(row).find("th, td").each(function(index, column) {
        rowData.push(column.innerText);
      });
      tableData.push(rowData.join(","));
    });
    data += tableData.join("\n");
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {
      type: "text/csv"
    })) + '/>');


    $('#download-link')[0].click();
    $('#download-link').remove();
  });
});
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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<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>csv</button>
</div>


3
投票

这是一个非常快速的 CoffeeScript/jQuery 示例

csv = []
for row in $('#sometable tr')
  csv.push ("\"#{col.innerText}\"" for col in $(row).find('td,th')).join(',')
output = csv.join("\n")

2
投票

感谢

gene tsai
,以下是对其代码的一些修改,以便在我的目标页面上运行:

csv = []
rows = $('#data tr');
for(i =0;i < rows.length;i++) {
    cells = $(rows[i]).find('td,th');
    csv_row = [];
    for (j=0;j<cells.length;j++) {
        txt = cells[j].innerText;
        csv_row.push(txt.replace(",", "-"));
    }
    csv.push(csv_row.join(","));
}
output = csv.join("\n")

改进:

  • 使用通用 JavaScript
    for
    循环
  • 确保每个单元格没有逗号

1
投票

您可以使用 Chrome 扩展程序,我尝试过几次,效果很好。

https://chrome.google.com/webstore/search/html%20table%20to%20csv?_category=extensions

安装后,在任何带有表格的网页上,如果您单击此扩展程序的图标,它会显示页面中的所有表格,当您将鼠标悬停在其列出的表格上时突出显示每个表格,单击允许您将其复制到剪贴板或保存到 Google 文档。

它非常适合我的需要,即偶尔将基于网络的表格数据转换为我可以使用的电子表格。


0
投票

如果不经常需要,请尝试几个 Firefox 插件之一,这些插件有助于将 HTML 表格数据复制到剪贴板(例如,https://addons.mozilla.org/en-US/firefox/addon/dafizilla-table2clipboard/) 。例如,对于“table2clipboard”附加组件:

  1. 在 Firefox 中安装插件
  2. 在 Firefox 中打开网页(带有表格)
  3. 右键单击表格中的任意位置并选择“复制整个表格”
  4. 启动电子表格应用程序,例如 LibreOffice Calc
  5. 粘贴到电子表格中(根据需要选择适当的分隔符)
  6. 将电子表格保存/导出为 CSV。

0
投票

我简要介绍了一种使用 Google 电子表格(

importHTML
)和 Python(Pandas
read_html
to_csv
)实现此目的的简单方法,以及我的 SO 答案中的示例 Python 脚本:https:/ /stackoverflow.com/a/28083469/1588795.


0
投票

下面是纯js和基于html的解决方案,它将html转换为csv并导出文件

function downloadCSV() {

                // Getting values of current time for generating the file name, with current date and time
                const dateTime = new Date();
                const day = dateTime.getDate();
                const month = dateTime.getMonth() + 1;
                const year = dateTime.getFullYear();
                const hour = dateTime.getHours();
                const minute = dateTime.getMinutes();
                const postfix = `${day}.${month}.${year}_${hour}.${minute}`;

                //get the table by its id
                const table = document.getElementById('shiftTable');
                let csvContent = '';
                //traverse the table rows and create csv contents
                for (let i = 0; i < table.rows.length; i++) {
                    let row = table.rows[i];
                    let rowData = [];
                    //traverse the table columns and create comma separeted columns
                    for (let j = 0; j < row.cells.length; j++) {
                        let cell = row.cells[j];
                        //don't include the columns which have 'ignore-column' attribute, in case some column need to be removed from csv
                        if (cell.attributes.getNamedItem('ignore-column') == null) {
                            rowData.push(cell.textContent.replace(/,/g, ''));
                        }
                    }
                    //add line feed to complete a row
                    csvContent += rowData.join(',') + '\r\n';
                }
                //xreatea a blob with csv contents
                const blob = new Blob([csvContent], { type: 'text/csv' });
                //create a url to link to csv content blob
                const url = URL.createObjectURL(blob);
                //create anchor to point to url
                const a = document.createElement('a');
                a.href = url;
                //download the file with date time in name
                a.download = `shifts_${postfix}.csv`;
                //add the anchor to document, so it can be clicked
                document.body.appendChild(a);
                //call the click event, so the csv contents can be downloadws
                a.click();
                //remove the anchor as its purpose is served
                document.body.removeChild(a);

            }
  <button class="mt-1 btn btn-complete btn-cons btnGo" onclick="downloadCSV()">Export</button>
<table class="table" :class="loading ? 'loading' : ''" id="shiftTable">
            <thead>
                <tr>
                    <th><span>Employee</span></th>
                    <th><span>Clocked In</span></th>
                    <th><span>Clocked Out</span></th>
                    <th><span >Duration</th>
                    <th ignore-column="true">Action</th>
                </tr>
            </thead>
            <tbody>
<tr><td>Khurram</td> <td>Tue Oct 08 2024 12:11:00 p.m.</td> <td>Sun Oct 13 2024 8:22:00 p.m.</td> <td>8 hr(s), 11 min(s)</td> <td ignore-column="true"><a href="/Shift/10HYAGKNRFSX2">View</a></td></tr>
              <tr><td>Khurram</td> <td>Thu Oct 03 2024 9:12:00 p.m.</td> <td>Thu Oct 03 2024 9:13:00 p.m.</td> <td>0 hr(s), 1 min(s)</td> <td ignore-column="true"><a href="/Shift/WZXZH7AKXBWP8">View</a></td></tr>
            </tbody>
        </table>

要忽略任何列(有时我们显示更多列,这些列对于 csv 来说毫无用处),请为其添加“ignore-column”属性(参见 html) enter image description here

要验证 csv 文件内容,您可以使用链接

https://www.convertcsv.com/csv-viewer-editor.htm

© www.soinside.com 2019 - 2024. All rights reserved.