Third-party libraries
You can use sheetJS, a third-party plug-in library, as follows:
function readFile () {
return new Promise((resolve, reject) = > {
let reader = new FileReader()
reader.onload = (e) = > {
resolve(e)
}
reader.onerror = e= > {
reject(e)
}
if (type === 'text') {
reader.readAsText(file)
} else if (type === 'binary') {
reader.readAsBinaryString(file)
} else {
reader.readAsArrayBuffer(file)
}
})
}
Copy the code
async function getData (file) {
const e = await readFile(file)
let out = {}
let headers = {}
// Read file data
let e = await readFile(file.raw, 'text')
let data = e.target.result
// Read excel data
let workbook = window.XLSX.read(data, { type: 'array'.raw: true.codepage: 936 })
// Read all sheet data
workbook.SheetNames.forEach(n= > {
out[n] = window.XLSX.utils.sheet_to_json(workbook.Sheets[n], { cellDates: true.raw: true })
// Read data in landscape mode, the first behavior is the title array
headers[n] = window.XLSX.utils.sheet_to_json(workbook.Sheets[n], { header: 1.cellDates: true.raw: true})})// Get data from the first sheet
let sheetName = workbook.SheetNames[0]
arr = out[sheetName] // All data
header = header[sheetName]
}
Copy the code
Use the above code to find read UTF-8 format CSV file, Chinese garbled, so modify to the following code to solve the problem.
The CSV file is read using the readAsText method of the FileReader object, and the text file is prefixed with \ufeff (UTF-8 BOM identifier) so that it can be identified as UTF-8 BOM, and read again with FileReader
async function getData (file) {
const e = await readFile(file)
let out = {}
let headers = {}
// Read file data
let e = await readFile(file.raw, 'text')
let data = e.target.result
let buf = new Uint8Array(data)
// UtF8 format files will read Chinese garbled, add BOM, change the format to UTF-8 with BOM
let blob = new Blob(['\ufeff' + data], { type: 'text/csv; charset=utf-8' })
e = await readFile(blob)
data = e.target.result
// Read excel data
let workbook = window.XLSX.read(data, { type: 'array'.raw: true.codepage: 936 })
// Read all sheet data
workbook.SheetNames.forEach(n= > {
out[n] = window.XLSX.utils.sheet_to_json(workbook.Sheets[n], { cellDates: true.raw: true })
// Read data in landscape mode, the first behavior is the title array
headers[n] = window.XLSX.utils.sheet_to_json(workbook.Sheets[n], { header: 1.cellDates: true.raw: true})})// Get data from the first sheet
let sheetName = workbook.SheetNames[0]
arr = out[sheetName] // All data
header = header[sheetName]
}
Copy the code