Commit 6e0c70f415b2d65b188d327c3f4ca4ff9f230ecc

Authored by 无木
1 parent 01b667fa

fix(import-excel): support datetime raw data import

importExcel支持导入原始日期时间数据

fixed: #1215
src/components/Excel/src/ImportExcel.vue
... ... @@ -15,12 +15,25 @@
15 15 <script lang="ts">
16 16 import { defineComponent, ref, unref } from 'vue';
17 17 import XLSX from 'xlsx';
  18 + import { dateUtil } from '/@/utils/dateUtil';
18 19  
19 20 import type { ExcelData } from './typing';
20 21 export default defineComponent({
21 22 name: 'ImportExcel',
  23 + props: {
  24 + // 日期时间格式。如果不提供或者提供空值,将返回原始Date对象
  25 + dateFormat: {
  26 + type: String,
  27 + },
  28 + // 时区调整。实验性功能,仅为了解决读取日期时间值有偏差的问题。目前仅提供了+08:00时区的偏差修正值
  29 + // https://github.com/SheetJS/sheetjs/issues/1470#issuecomment-501108554
  30 + timeZone: {
  31 + type: Number,
  32 + default: 8,
  33 + },
  34 + },
22 35 emits: ['success', 'error'],
23   - setup(_, { emit }) {
  36 + setup(props, { emit }) {
24 37 const inputRef = ref<HTMLInputElement | null>(null);
25 38 const loadingRef = ref<Boolean>(false);
26 39  
... ... @@ -51,10 +64,28 @@
51 64 */
52 65 function getExcelData(workbook: XLSX.WorkBook) {
53 66 const excelData: ExcelData[] = [];
  67 + const { dateFormat, timeZone } = props;
54 68 for (const sheetName of workbook.SheetNames) {
55 69 const worksheet = workbook.Sheets[sheetName];
56 70 const header: string[] = getHeaderRow(worksheet);
57   - const results = XLSX.utils.sheet_to_json(worksheet);
  71 + let results = XLSX.utils.sheet_to_json(worksheet, {
  72 + raw: true,
  73 + dateNF: dateFormat, //Not worked
  74 + }) as object[];
  75 + results = results.map((row: object) => {
  76 + for (let field in row) {
  77 + if (row[field] instanceof Date) {
  78 + if (timeZone === 8) {
  79 + row[field].setSeconds(row[field].getSeconds() + 43);
  80 + }
  81 + if (dateFormat) {
  82 + row[field] = dateUtil(row[field]).format(dateFormat);
  83 + }
  84 + }
  85 + }
  86 + return row;
  87 + });
  88 +
58 89 excelData.push({
59 90 header,
60 91 results,
... ... @@ -76,7 +107,7 @@
76 107 reader.onload = async (e) => {
77 108 try {
78 109 const data = e.target && e.target.result;
79   - const workbook = XLSX.read(data, { type: 'array' });
  110 + const workbook = XLSX.read(data, { type: 'array', cellDates: true });
80 111 // console.log(workbook);
81 112 /* DO SOMETHING WITH workbook HERE */
82 113 const excelData = getExcelData(workbook);
... ...
src/views/demo/excel/ImportExcel.vue
1 1 <template>
2 2 <PageWrapper title="excel数据导入示例">
3   - <ImpExcel @success="loadDataSuccess">
  3 + <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
4 4 <a-button class="m-3"> 导入Excel </a-button>
5 5 </ImpExcel>
6 6 <BasicTable
... ...