解决前端xlsx.js读取Excel时间格式缺失43秒问题

作者:阿沐时间:2026-10-31 12:52:57浏览:657

本文介绍在使用xlsx.js读取Excel文件时,日期数据常出现缺失43秒的问题。通过设置cellDates配置项获取标准时间格式,并针对23:59:17这一特定时间戳增加44秒进行修正,同时结合Element Plus组件实现文件的上传与导出功能。

xlsx.js读取Excel时间格式缺失43秒问题

在使用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秒。解决思路较为直接:判断时间字符串是否包含'23:59:17',若是,则直接增加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组件读取Excel文件步骤

补充说明:使用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秒的相关内容,请搜索本站过往文章或继续浏览下方相关文章,希望大家以后多多支持本站!

作者最新文章