1. Export CSV
CSV (Comma Separated Values) is a common file format. For the definition, see RFC 4180
It separates different records with a newline character, separates different fields in each record with commas, and each field may or may not be enclosed in double quotes
If a field contains double quotes, newline characters, or commas, the field must be surrounded by double quotes, and the double quotes must be escaped with double quotes
Here is the pure front-end export CSV file code:
function isMSbrowser() {
const userAgent = window.navigator.userAgent
return userAgent.indexOf('Edge')! = = -1 || userAgent.indexOf('Trident')! = = -1
}
function format(data) {
return String(data).replace(/"/g.'" "').replace(/(^[\s\S]*$)/.'" $1")}function saveCSV(title, head, data) {
let wordSeparator = ', '
let lineSeparator = '\n'
let reTitle = title + '.csv'
let headBOM = '\ufeff'
let headStr = head ? head.map(item= > format(item)).join(wordSeparator) + lineSeparator : ' '
let dataStr = data ? data.map(row= > row.map(item= > format(item)).join(wordSeparator)).join(lineSeparator) : ' '
return isMSbrowser()
? new Promise(resolve= > { / / Edge, IE11
let blob = new Blob([headBOM + headStr + dataStr], { type: 'text/plain; charset=utf-8' })
window.navigator.msSaveBlob(blob, reTitle)
resolve()
})
: new Promise(resolve= > { / / Chrome, Firefox
let a = document.createElement('a')
a.href = 'data:text/csv; charset=utf-8,' + headBOM + encodeURIComponent(headStr + dataStr)
a.download = reTitle
a.click()
resolve()
})
}
Copy the code
Here is an example in use:
let title = 'test'
let head = ['key'.'value']
let data = [
['a'.'I'm normal text'],
['b'.'I'm double quotes.'],
['c'.'I am, little comma,'],
['d'.'I am \n newline']
]
saveCSV(title, head, data).then(() = > {
console.log('success')})Copy the code
2. Export JSON
JSON is also a very common data format, especially in front – and back-end data exchanges, which I won’t expand on here
Here is the code for the pure front-end export JSON file:
function isMSbrowser() {
const userAgent = window.navigator.userAgent
return userAgent.indexOf('Edge')! = = -1 || userAgent.indexOf('Trident')! = = -1
}
function saveJSON(title, data) {
let reTitle = title + '.json'
let dataStr = data ? JSON.stringify(data) : ' '
return isMSbrowser()
? new Promise(resolve= > { / / Edge, IE11
let blob = new Blob([dataStr], { type: 'text/plain; charset=utf-8' })
window.navigator.msSaveBlob(blob, reTitle)
resolve()
})
: new Promise(resolve= > { / / Chrome, Firefox
let a = document.createElement('a')
a.href = 'data:text/json; charset=utf-8,' + dataStr
a.download = reTitle
a.click()
resolve()
})
}
Copy the code
Here is an example in use:
let title = 'test'
let data = {
'a': 'Hello'.'b': 'Hi'.'c': 'Goodbye'.'d': 'Bye'
}
saveJSON(title, data).then(() = > {
console.log('success')})Copy the code