@TOC# 学习目标:

提示:这里可以添加学习目标
例如:一周掌握 Java 入门知识


学习内容:前端项目中导出excel和解析excel

提示:这里可以添加要学的内容
例如:
1、 解析excel
2、 导出excel


解决方案:

1.解析exce

vue2+elementui(二次封装的组件 UploadExecl.vue)

前提资源下载:
	npm i xlsx@0.17.4
<template>
  <div>
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
    <div class="mian">
      <div class="left">
        <el-button
          type="primary"
          :loading="loading"
          @click="handleUpload"
        >点击上传</el-button>
      </div>
      <div
        class="right"
        @drop="handleDrop"
        @dragover="handleDragover"
        @dragenter="handleDragover"
      >
        <i class="el-icon-upload" />
        <span>将文件拖到此处</span>
      </div>
    </div>
    <!-- <div
      class="drop"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      Drop excel file here or
      <el-button
        :loading="loading"
        style="margin-left: 16px"
        size="mini"
        type="primary"
        @click="handleUpload"
      >
        Browse
      </el-button>
    </div> -->
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  name: 'UploadExecl',
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel

      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped lang="scss">
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.mian {
  margin: 0 auto;
  width: 600px;
  height: 220px;
  display: flex;
  border: 1px dashed #ccc;
  .left {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1px dashed #ccc;
  }
  .right {
    flex: 1;
    text-align: center;
    margin: auto;
    .el-icon-upload {
      display: block;
      font-size: 80px;
      color: #5687fe;
    }
  }
}
</style>

使用

注意点:传入两个函数onSuccess(文件导入成功的回调),beforeUpload(文件解析前的回调2)

<template>
  <div>
    <UploadExecl :on-success="onSuccess"></UploadExecl>
</div>
<template>


methods:{
    async onSuccess({ header, results }) {
      // 把execl中的中文字符修改为英文的并且和后端对应
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
      }
      const newArr = results.map((item) => {
        const newObj = {}
        Object.keys(item).forEach((item2) => {
          if (
            userRelations[item2] === 'timeOfEntry' ||
            userRelations[item2] === 'correctionTime'
          ) {
            newObj[userRelations[item2]] = this.formatDate(item[item2])
            return
          }
          newObj[userRelations[item2]] = item[item2]
        })
        return newObj
      })
      console.log(newArr, '4')
    },
    // excel时间格式处理
    formatDate(numb) {
      const time = new Date((numb - 1) * 24 * 3600000 - 8 * 24 * 60 * 60)
      time.setYear(time.getFullYear() - 70)
      return time
    },
 }

2.前端导出execl

npm i xlsx@0.17.4

在utils下新建excel.js

import XLSX from 'xlsx'

function autoWidthFunc(ws, data) {
	// set worksheet max width per col
	const colWidth = data.map((row) =>
		row.map((val) => {
			var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g') //检测字符串是否包含汉字
			if (val == null) {
				return { wch: 10 }
			} else if (reg.test(val)) {
				return { wch: val.toString().length * 2 }
			} else {
				return { wch: val.toString().length }
			}
		})
	)
	// start in the first row
	const result = colWidth[0]
	for (let i = 1; i < colWidth.length; i++) {
		for (let j = 0; j < colWidth[i].length; j++) {
			if (result[j].wch < colWidth[i][j].wch) {
				result[j].wch = colWidth[i][j].wch
			}
		}
	}
	ws['!cols'] = result
}

function jsonToArray(key, jsonData) {
	return jsonData.map((v) =>
		key.map((j) => {
			return v[j]
		})
	)
}

const exportArrayToExcel = ({ key, data, title, filename, autoWidth }) => {
	const wb = XLSX.utils.book_new()
	const arr = jsonToArray(key, data)
	arr.unshift(title)
	const ws = XLSX.utils.aoa_to_sheet(arr)
	if (autoWidth) {
		autoWidthFunc(ws, arr)
	}
	XLSX.utils.book_append_sheet(wb, ws, filename)
	XLSX.writeFile(wb, filename + '.xlsx')
}

export default {
	exportArrayToExcel
}

在使用的地方导入使用

import excel from './utils/excel'



methods:{
	    exportExcel() {
      const params = {
        title: ['date', 'name', 'address', 'imgae'],
        key: ['date', 'name', 'address', 'imgae'],
        data: this.tableData, // 数据源
        autoWidth: true, //autoWidth等于true,那么列的宽度会适应那一列最长的值
        filename: '清单',
      }
      excel.exportArrayToExcel(params)
    },
}
Logo

前往低代码交流专区

更多推荐