在使用 xlsx 读取 excel 的时间格式的数据时,如 ‘2023-11-30’,‘2023/11/30’ ,默认会读取一串数字字符串,如:‘45260’,此时需要在 read 的时候传入一个配置项:
import { read } from 'xlsx'
const workbook = read(filedata, {
type: 'binary',
celldates: true, // 读取日期格式的数据
})此时拿到的是标准的时间格式 :‘wed nov 29 2023 23:59:17 gmt+0800(中国标准时间)’ ,这个时间格式是带时区的,有没有发现,只要输入年月日,读到的数据总是差 43 秒,解决思路也很粗暴,判断是这个时间,直接加 44 秒。
if(datestr){
if(datestr?.includes('23:59:17')) {
datestr = dayjs(datestr).add(44, 'second')
}
// 如果需要可以格式化成需要的格式
const dayobj = dayjs(datestr.tostring())
if(dayobj.isvalid()) {
datestr = dayobj.format('yyyy-mm-dd')
}
return datestr
}附:element-plus el-upload 读取 xlsx 格式的 excel 文件的步骤
<template>
<el-upload
ref="uploadref"
action=""
:auto-upload="false"
:on-change="onselectfile"
:on-remove="onremovefile"
:file-list="filelist"
accept=".xlsx">
<el-button type="primary">导入</el-button>
</el-upload>
<br>
<el-button @click="handleexport">导出</el-button>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { uploadfile, uploadrawfile } from 'element-plus'
import { read, utils, writefile } from 'xlsx'
type iexcel = record<string, array<record<string, string>>>
const filelist = ref<{name: string}[]>([])
const importdata = ref<iexcel | null>(null)
async function onselectfile(file: uploadfile) {
reset()
if(file.raw) {
if(file.raw.type !== 'application/vnd.openxmlformats-offocedocument.spreadsheetml.sheet') {
return '请上传 xlsx 格式文件'
}
if(file.raw.size / 1024 / 1024 > 10) {
return '文件格式不能超过 10m'
}
filelist.value.push({ name: file.raw.name })
// 解析文件
const raw = file.raw
const res = await readfile2binary(raw)
const resinfo: iexcel = {} // 解析结果
if(res) {
const workbook = read(res, {
type: 'binary',
celldates: true,
})
workbook.sheetnames.foreach((sheetname) => {
const exceldata: record<string, string>[] = utils.sheet_to_json(workbook.sheets[sheetname])
resinfo[sheetname] = exceldata
})
// 检查数据的合法性
// if(validxlsx(resinfo)) {
// importdata.value = resinfo
// }
importdata.value = resinfo
}
}
}
// 重置
function reset() {
filelist.value = []
// ...
}
function onremovefile() {
reset()
}
/**
* 将 el-upload 选择的文件读取成二进制
* @param raw
*/
function readfile2binary(raw: uploadrawfile) {
return new promise((resolve, reject) => {
const reader = new filereader()
reader.readasbinarystring(raw)
reader.onload = (ev) => {
if(ev.target) {
resolve(ev.target.result)
} else {
reject()
}
}
})
}
/**
* 导出
*/
function handleexport() {
const sheetlist = {
sheet1: [],
sheet2: [],
}
const filename = 'xxx.xlsx'
const workbook = utils.book_new()
for(const key in sheetlist) {
const sheetname = key
const worksheet = utils.aoa_to_sheet(sheetlist[key])
utils.book_append_sheet(workbook, worksheet,sheetname)
}
writefile(workbook, filename, {
booktype: 'xlsx',
})
}
</script>总结
到此这篇关于解决前端使用xlsx.js工具读取excel遇到时间日期少43秒问题的文章就介绍到这了,更多相关前端读取excel时间日期少43秒内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论