export html table to csv

后端 未结 8 2045
走了就别回头了
走了就别回头了 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 19:04

    Used the answer above, but altered it for my needs.

    I used the following function and imported to my REACT file where I needed to download the csv file.

    I had a span tag within my th elements. Added comments to what most functions/methods do.

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

    When user click export to csv it trigger the following function in react.

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

    Example html table elems.

      
              {this.renderData()}
            
    Timestamp full time current rate alt view Battery Voltage current voltage Temperature 1 [C] Temperature 2 [C] Time & Date

提交回复
热议问题