Article directory
1. Demand
- Provide an Excel file and export the contents into a JSON array
- Provide a JSON array, generate an Excel file and download it
sheet
2. Realize
1. Installation steps
npm install xlsx --save
2. use
import * as XLSX from 'xlsx' // Vue3 版本
3. Export
const ExportXlsx = () => {
// 创建工作表
const data = XLSX.utils.json_to_sheet(props.table.tableData)
// 创建工作簿
const wb = XLSX.utils.book_new()
// 将工作表放入工作簿中
XLSX.utils.book_append_sheet(wb, data, 'data')
// 生成文件并下载
XLSX.writeFile(wb, 'test.xlsx')
}
After exporting, it is found that the data structure is not what we want. At this time, it can be converted by the following method.
let head = {
date: '日期',
name: '姓名',
address: '地址',
}
const list = props.table.tableData.map(item => {
const obj = {
}
for (const k in item) {
if (head[k]) {
obj[head[k]] = item[k]
}
}
return obj
})
change column width
4. Import
const ImportXlsx = e => {
const file = e.target.files[0]
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = e => {
let data = e.target.result
constworkbook = XLSX.read(data, {
type: 'binary', cellDates: true })
const wsname = workbook.SheetNames[0]
const outdata = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
console.log(outdata);
}
}
If there is a date in excel, you need to parse the content of the time format.
XLSL.read will be parsed as a timestamp string of days by default (the number of days from 1900 to the current date)
解决办法:
const workbook = XLSX.read(data, {
type: 'binary',
cellDates: true //设为true,将天数的时间戳转为时间格式
})
Convert to China Standard Time, what I want in the end is to convert to the time format I want, and I need the moment tool class
import moment from "moment";
Points to note: After xlsx parses the time content in excel, it will be smaller by one day, such as 2020/11/3, and xlsx will be parsed into Mon Nov 02 2020 23:59:17 GMT
+0800, which is 43 seconds shorter and then converted to Date time: Mon Nov 02 2020 23:59:17
GMT+0800 will be converted to 2020/11/2, so it needs to be +1 day after the moment conversion
// 这里我将日期和表格中文转换放在一起处理了
const key = {
日期: 'date',
姓名: 'name',
地址: 'address',
}
const deal = data => {
data.forEach(item => {
Object.keys(item).map(keys => {
let newKey = key[keys]
if (newKey) {
item[newKey] = item[keys]
delete item[keys]
}
})
})
data.forEach(item => {
item.date = moment(item.date).add(1, 'd').format('YYYY-MM-DD')
})
return data
}