-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (77 loc) · 2.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function getType(item) {
return Object.prototype.toString.call(item).slice(8, -1)
}
function transSpecialChar(s) {
s = String(s)
if (s.indexOf(',') > -1 || s.indexOf('"') > -1) {
s = s.replace(/"/g, '""')
return `"${s}"`
}
return s
}
export default class CSVExporter {
constructor(options) {
this.data = options.data || []
this.fileName = `${options.fileName || new Date()}.csv`
this.csv = ''
this.columns = options.columns || []
let header = ''
this.columns.forEach((column) => {
let title = `${getType(column) === 'Object' ? column.title : column}`
title = transSpecialChar(title)
header += `${title},`
})
this.csv += `${header.slice(0, -1)}\r\n`
if (this.columns.length) {
this.data.forEach(function(item) {
let row = ''
let value = ''
this.columns.forEach(function(column, idx) {
value = getType(item) === 'Object' ? item[column.key || column.title] : item[idx]
if (getType(column) === 'Object' && getType(column.formatter) === 'Function') {
value = column.formatter(value, item)
}
value = transSpecialChar(value)
row += `${value},`
})
this.csv += `${row.slice(0, -1)}\r\n`
}, this)
}
}
getContent() {
return this.csv
}
export () {
const content = `\uFEFF${this.getContent()}`
if (window.Blob) {
const data = new Blob(
[content], {
type: 'text/csv'
}
)
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(data, this.fileName)
} else if (window.URL && window.URL.createObjectURL) {
const url = window.URL.createObjectURL(data)
const alink = document.createElement('a')
alink.id = 'downloadCSVLink'
alink.href = url
document.body.appendChild(alink)
const linkDom = document.getElementById('downloadCSVLink')
linkDom.setAttribute('download', this.fileName)
linkDom.click()
document.body.removeChild(linkDom)
window.URL.revokeObjectURL(url)
}
} else {
const frame = document.createElement('iframe')
document.body.appendChild(frame)
frame.contentWindow.document.open('text/html', 'replace')
frame.contentWindow.document.write(`sep=,\r\n${content}`)
frame.contentWindow.document.close()
frame.contentWindow.focus()
frame.contentWindow.document.execCommand('SaveAs', true, this.fileName)
document.body.removeChild(frame)
}
}
}