html table导出csv,javascript - export html table to csv - Stack Overflow

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.

Timestamp

full time

current rate

alt view

Battery Voltage

current voltage

Temperature 1

[C]

Temperature 2

[C]

Time & Date

{this.renderData()}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值