将html表导出到csv

时间:2013-03-21 12:12:36

标签: javascript jquery node.js html-table export-to-csv

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

9 个答案:

答案 0 :(得分:35)

仅使用jQuery,vanilla Javascripttable2CSV库:

export-to-html-table-as-csv-file-using-jquery

将此代码放入要加载到head部分的脚本中:

 $(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);
        });
    });
})

注意:

需要jQuerytable2CSV:在上述脚本之前向两个库添加脚本引用。

table选择器用作示例,可以根据您的需要进行调整。

它仅适用于支持Data URI完全支持的浏览器:Firefox,Chrome和Opera,而非IE,仅支持Data URIs将二进制图像数据嵌入页面。

要获得完全的浏览器兼容性,您必须使用稍微不同的方法,该方法需要服务器端脚本echo CSV。

答案 1 :(得分: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>

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

答案 2 :(得分:6)

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

data:application/csv;charset=utf-8,content_encoded_as_url

数据URI将类似于:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

您可以通过以下方式调用此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>

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

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

答案 3 :(得分:2)

我发现有一个库。见这里的例子:

https://editor.datatables.net/examples/extensions/exportButtons.html

除了上面的代码之外,还加载了以下Javascript库文件以供在此示例中使用:

在HTML中,包括以下脚本:

class: ['text-white', 'fullwidth-figure']

通过添加以下脚本启用按钮:

jquery.dataTables.min.js   
dataTables.editor.min.js   
dataTables.select.min.js
dataTables.buttons.min.js  
jszip.min.js    
pdfmake.min.js
vfs_fonts.js  
buttons.html5.min.js    
buttons.print.min.js

由于某种原因,excel导出会导致文件损坏,但可以修复。或者,禁用excel并使用csv export。

答案 4 :(得分:2)

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

    
function Result(props) {
    const { image, title, bodyText, btnText, btnUrl, btnColor } = props;

    return <>{`<!doctype html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
      <title> ${title} </title>
      <!--[if !mso]><!-- -->
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <!--<![endif]-->
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <style type="text/css">
    
        body {
          margin: 0;
          padding: 0;
          -webkit-text-size-adjust: 100%;
          -ms-text-size-adjust: 100%;
        }
    
        table,
        td {
          border-collapse: collapse;
          mso-table-lspace: 0pt;
          mso-table-rspace: 0pt;
        }
    
      </style>
      <!--[if !mso]><!-->
      <style type="text/css">
        @media only screen and (min-width:480px) {
          .mj-column-per-100 {
            width: 100% !important;
            max-width: 100%;
          }
          .mj-column-px-600 {
            width: 600px !important;
            max-width: 600px;
          }
        }
      </style>
      <style type="text/css">
        @media only screen and (max-width: 480px) {
          .small p {
            font-size: 9px !important;
          }
        }

      </style>
    </head>
    
    <body>
      <div style="">
        <table class="body" cellpadding="0" align="center" cellspacing="0">
          <tr>
            <td align="center" style="text-align:center; padding:0px 0px 0px 0px;">
              <font style="display: none; max-height: 0px; overflow: hidden;">&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;</font>
            </td>
          </tr>
        </table>
        <!--[if mso | IE]>
          <table
             align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
          >
            <tr>
              <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
          <![endif]-->
        <div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;">
          <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;">
            <tbody>
              <tr>
                <td style="direction:ltr;font-size:0px;padding:5px 0 5px 0;text-align:center;vertical-align:top;">
                  <!--[if mso | IE]>
                      <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    
            <tr>
          
                <td
                   class="" style="vertical-align:top;width:600px;"
                >
              <![endif]-->
                  <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                    <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
                      <tr>
                        <td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;">
                          <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;border-spacing:0px;">
                            <tbody>
                              <tr>
                                <td style="width:200px;"> <img alt="Company Name" height="auto" src="" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;"
                                    width="200"> </td>
                              </tr>
                            </tbody>
                          </table>
                        </td>
                      </tr>
                    </table>
                  </div>
                  <!--[if mso | IE]>
                </td>
              
            </tr>
          
                      </table>
                    <![endif]-->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!--[if mso | IE]>
              </td>
            </tr>
          </table>
          
          <table
             align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
          >
            <tr>
              <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
          <![endif]-->
        <div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;">
          <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;">
            <tbody>
              <tr>
                <td style="direction:ltr;font-size:0px;padding:0px;text-align:center;vertical-align:top;">
                  <!--[if mso | IE]>
                      <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    
            <tr>
          
                <td
                   class="" style="vertical-align:top;width:600px;"
                >
              <![endif]-->
                  <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                    <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%">
                      <tbody>
                        <tr>
                          <td style="vertical-align:top;padding:0px;">
                            <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%">
                              <tr>
                                <td align="center" style="font-size:0px;padding:0px;word-break:break-word;">
                                  <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;border-spacing:0px;">
                                    <tbody>
                                      <tr>
                                        <td style="width:600px;"> <img alt="" height="auto" src="http://image.e.campingworldrv.com/lib/fe9915737d640c7f75/m/1/648eb085-3d86-4be1-a8e7-f3d8f8023c53.png" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;"
                                            width="600"> </td>
                                      </tr>
                                    </tbody>
                                  </table>
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <!--[if mso | IE]>
                </td>
              
            </tr>
          
                      </table>
                    <![endif]-->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!--[if mso | IE]>
              </td>
            </tr>
          </table>
          
          <table
             align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
          >
            <tr>
              <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
          <![endif]-->
        <div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;">
          <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;">
            <tbody>
              <tr>
                <td style="direction:ltr;font-size:0px;padding:5px 10px 5px 10px;text-align:center;vertical-align:top;">
                  <!--[if mso | IE]>
                      <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    
            <tr>
          
                <td
                   class="" style="vertical-align:top;width:580px;"
                >
              <![endif]-->
                  <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                    <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
                      <tr>
                        <td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;">
                          <div style="font-family:Arial, Helvetica, sans-serif;;font-size:13px;line-height:1;text-align:center;color:#000000;"> <span style="color: #000000; font-weight: bold; font-size:24px">${age} ${bodyText}</span><br><br><span style="font-size: 14px; color: #000000;">${bodyText}</span> </div>
                        </td>
                      </tr>
                      <tr>
                        <td align="center" vertical-align="middle" style="font-size:0px;padding:10px 25px;word-break:break-word;">
                          <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;">
                            <tr>
                              <td align="center" bgcolor="#000000" role="presentation" style="border:none;border-radius:0px;cursor:auto;padding:10px 25px;background:#000000;" valign="middle"> <a href="#" style="background:#000000;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;font-weight:bold;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">
                  ${btnText}
                </a> </td>
                            </tr>
                          </table>
                        </td>
                      </tr>
                    </table>
                  </div>
                  <!--[if mso | IE]>
                </td>
              
            </tr>
          
                      </table>
                    <![endif]-->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!--[if mso | IE]>
              </td>
            </tr>
          </table>
          
          <table
             align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
          >
            <tr>
              <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
          <![endif]-->
        <div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;">
          <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;">
            <tbody>
              <tr>
                <td style="direction:ltr;font-size:0px;padding:5px 0px 5px 0px;text-align:center;vertical-align:top;">
                  <!--[if mso | IE]>
                      <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    
            <tr>
          
                <td
                   class="" style="vertical-align:top;width:600px;"
                >
              <![endif]-->
                  <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                    <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%">
                      <tbody>
                        <tr>
                          <td style="vertical-align:top;padding:0px;">
                            <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%">
                              <tr>
                                <td style="font-size:0px;padding:0px;word-break:break-word;">
                                  <p style="border-top:solid 1px #6a6a6a;font-size:1;margin:0px auto;width:100%;"> </p>
                                  <!--[if mso | IE]>
            <table
               align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 1px #6a6a6a;font-size:1;margin:0px auto;width:600px;" role="presentation" width="600px"
            >
              <tr>
                <td style="height:0;line-height:0;">
                  &nbsp;
                </td>
              </tr>
            </table>
          <![endif]-->
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <!--[if mso | IE]>
                </td>
              
            </tr>
          
                      </table>
                    <![endif]-->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!--[if mso | IE]>
              </td>
            </tr>
          </table>
        
          
          <table
             align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
          >
            <tr>
              <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
          <![endif]-->
        <div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;">
          <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;">
            <tbody>
              <tr>
                <td style="direction:ltr;font-size:0px;padding:0px 10px 20px 10px;text-align:center;vertical-align:top;">
                  <!--[if mso | IE]>
                      <table role="presentation" border="0" cellpadding="0" cellspacing="0">
                    
            <tr>
          
                <td
                   class="" style="vertical-align:top;width:580px;"
                >
              <![endif]-->
                  <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
                    <table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%">
                      <tbody>
                        <tr>
                          <td style="vertical-align:top;padding:0px;">
                            <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="" width="100%">
                              <tr>
                                <td align="center" style="font-size:0px;padding:0px;word-break:break-word;">
                                  <div style="font-family:Arial, Helvetica, sans-serif;;font-size:10px;line-height:1;text-align:center;color:#6a6a6a;"> Don't want anymore emails from us? <a href="http://www.unsubscribe.com/">Unsubscribe</a>
                                  </div>
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <!--[if mso | IE]>
                </td>
              
            </tr>
          
                      </table>
                    <![endif]-->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!--[if mso | IE]>
              </td>
            </tr>
          </table>
          <![endif]-->
      </div>
    </body>
    
    </html>`}</>;
}

function download(filename, text) {
    let element = document.createElement('a');
    element.setAttribute(
        'href',
        'data:text/plain;charset=utf-8,' + encodeURIComponent(text)
    );
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}

function BasicHtml(props) {
    const { title, children } = props;

    return (
        <html>
            <head>
                <title>{title}</title>
            </head>
            <body>{children}</body>
        </html>
    );
}

export default class FormComponent extends React.Component {
    state = { name: '', age: null, submitted: false };

    handleChange = e => {
        this.setState({ [e.target.name]: e.target.value });
    };

    handleSubmit = e => {
        e.preventDefault();
        this.setState({ submitted: true });
        this.generateHtmlFile();
    };

    generateHtmlFile = () => {
        const { name, age } = this.state;
        const formHtml = ReactDomServer.renderToStaticMarkup(
            <BasicHtml title={name}>
                <FormComponent />
            </BasicHtml>
        );
        const resultHtml = ReactDomServer.renderToStaticMarkup(
            <BasicHtml title={name}>
                <Result name={name} age={age} />
            </BasicHtml>
        );
        download('result.html', resultHtml);
        download('form.html', formHtml);
    };

    render() {
        const { name, age, submitted } = this.state;
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>
                        Name:{' '}
                        <input
                            name="name"
                            type="text"
                            value={this.state.name}
                            onChange={this.handleChange}
                            required
                        />
                    </label>
                    <br />
                    <br />
                    <label>
                        Age:{' '}
                        <input
                            name="age"
                            type="number"
                            value={this.state.age}
                            onChange={this.handleChange}
                            required
                        />
                    </label>
                    <br />
                    <br />
                    <input type="submit" value="Submit" />
                </form>
                <br />
                {submitted ? <Result name={name} age={age} /> : null}
            </div>
        );
    }
}
        
        ReactDOM.render(<FormComponent />, document.body);
    
    
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    
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);
}

(2)如果您要使用纯JavaScript库,FileSaver.js可以帮助您保存用于触发文件下载的代码段。此外,FileSaver.js将不负责构建导出内容。您必须以所需的格式自己构造内容。

答案 5 :(得分:1)

现代解决方案

这里提出的大多数解决方案都会与 td 元素中的嵌套表或其他元素中断。我经常在我的表格中使用其他元素,但只想导出最顶层的表格。我从 Calumah 那里获取了一些在此处找到的代码,并添加了一些现代 vanilla 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()
}

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

答案 6 :(得分:0)

使用上面的答案,但根据我的需要进行了更改。

我使用了以下功能,并将其导入到需要下载csv文件的 REACT 文件中。

我的span元素中有一个th标记。添加了对大多数功能/方法的注释。

import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';


export function tableToCSV(){
  let tableHeaders = Array.from(document.querySelectorAll('th'))
    .map(item => {
      // title = splits elem tags on '\n',
      // then filter out blank "" that appears in array.
      // ex ["Timestamp", "[Full time]", ""]
      let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
      return title
    }).join(",")

  const rows = Array.from(document.querySelectorAll('tr'))
  .reduce((arr, currRow) => {
    // if tr tag contains th tag.
    // if null return array.
    if (currRow.querySelector('th')) return arr

    // concats individual cells into csv format row.
    const cells = Array.from(currRow.querySelectorAll('td'))
      .map(item => item.innerText)
      .join(',')
    return arr.concat([cells])
  }, [])

return tableHeaders + '\n' + rows.join('\n')
}

export function downloadCSV(csv){
  const csvFile = new Blob([csv], { type: 'text/csv' })
  const downloadLink =  document.createElement('a')
  // sets the name for the download file
  downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
  // sets the url to the window URL created from csv file above
  downloadLink.href = window.URL.createObjectURL(csvFile)
  // creates link, but does not display it.
  downloadLink.style.display = 'none'
  // add link to body so click function below works
  document.body.appendChild(downloadLink)

  downloadLink.click()
}

当用户单击导出到csv时,它会在react中触发以下功能。

  handleExport = (e) => {
    e.preventDefault();
    const csv = tableToCSV()
    return downloadCSV(csv)
  }

示例html表元素。

  <table id="datatable">
        <tbody>
          <tr id="tableHeader" className="t-header">
            <th>Timestamp
              <span className="block">full time</span></th>
            <th>current rate
              <span className="block">alt view</span>
            </th>
            <th>Battery Voltage
              <span className="block">current voltage
              </span>
            </th>
            <th>Temperature 1
              <span className="block">[C]</span>
            </th>
            <th>Temperature 2
              <span className="block">[C]</span>
            </th>
            <th>Time & Date </th>
          </tr>

        </tbody>
        <tbody>
          {this.renderData()}
        </tbody>
      </table>
    </div>

答案 7 :(得分:0)

应该可以在每种现代浏览器上运行,并且没有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 https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
            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);
}

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

<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>

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

答案 8 :(得分:0)

我使用了上面发布的Calumah函数,但是他的代码确实存在问题。

行用分号连接

csv.push(row.join(';'));

但是生成的链接的内容类型为“ text / csv”

也许在Windows中这不是问题,但是在Mac的Excel中会出现问题。我将数组连接更改为逗号,并且效果很好。