export html table to csv

后端 未结 8 2044
走了就别回头了
走了就别回头了 2020-12-07 18:20

I am trying to add a feature of csv download option in my website. It should convert the html table present in the website in to csv content and make it downloadable. Ive be

8条回答
  •  盖世英雄少女心
    2020-12-07 18:59

    (1)This is the native javascript solution for this issue. It works on most of modern browsers.

    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);
    }
    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;
    }
    Name Author Description
    jQuery John Resig The Write Less, Do More, JavaScript Library.
    React Jordan Walke React makes it painless to create interactive UIs.
    Vue.js Yuxi You The Progressive JavaScript Framework.

    (2) If you want a pure javascript library, FileSaver.js could help you save the code snippets for triggering file download. Besides, FileSaver.js will not be responsible for constructing content for exporting. You have to construct the content by yourself in the format you want.

提交回复
热议问题