vue+element+xlsx parsing and uploading form

Important codes are marked in red

Plug-in components used

npm i element

npm i xlsx

There are differences in the introduction of vue3, the specific Baidu

html:

 <div class="crenter">

        <div>

          <el-card class="box-card">

            <el-upload ref="upload" accept=".xls,.xlsx"  action="#"  :auto-upload="false"

         :multiple="false" :file-list="fileList"  :before-upload="beforeUpload" 

          :http-request="uploadHttpRequest"  :on-remove="fileRemove"    :on-change="fileChange"

           drag   >

              <img class="upImg" src="../../style/img/up.png" alt="" />

              <el-button class="buttonUp" type="primary">上传excel</el-button>

              <div class="el-upload__text">Or drag and drop a file</div>

            </el-upload>

          </el-card>

          <div class="el-upload__tip">Only upload excel files, and no more than 500kb</div>

        </div>

        <div>

          <el-button style="width: 450px; margin: 20px auto; padding: 15px" type="primary"         @click="submitUpload">确认上传</el-button>

          </div>

      </div>

js:

Import components

import XLSX from '../../../node_modules/xlsx'

export default {

  data() {

    return {

      options: [

        {

          value: 1,

          label: 'whole package',

        },

        {

          value: 2,

          label: 'loose package',

        },

        {

          value: 3,

          label: 'single source',

        },

      ],

      is_type: '',

      action: process.env.VUE_APP_BASE_API + '/business/BizMaterialSum/importData',

      // user import parameters

      fileList: [],

      // read

      defaultIndex: 0, // display the first worksheet by default

      wb: null, // worksheet object

      formData: {},

    }

  },

  created() {},

  methods: {

    beforeUpload(file) {

      //file type

      const isType = file.type === 'application/vnd.ms-excel'

      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      const fileType = isType || isTypeComputer

      if (!fileType) {

        this.$message.error('Upload files can only be in xls/xlsx format!')

      }

      // The file size is limited to 10M

      const fileLimit = file.size / 1024 / 1024 < 10

      if (!fileLimit) {

        this.$message.error('The uploaded file size does not exceed 10M!')

      }

      return fileType && fileLimit

    },

    // Customize the upload method, param is the default parameter, you can get the file information, the specific information is as follows

    uploadHttpRequest(param) {

      // const formData = new FormData() //FormData object, adding parameters can only be added in the form of append('key', value)

      // formData.append('file', param.file) //Add file object

      // formData.append('uploadType', this.is_type) //Parameters to be passed by the interface

      // // call interface api

      // importData(formData).then((data) => {

      //   if (data.code == 200) {

      // this.msgSuccess('success')

      // param.onSuccess() // Successfully uploaded files display a green tick

      //     this.fileList = []

      //     this.is_type = ''

      //   } else {

      //     this.msgError(data.msg)

      //   }

      // })

    },

    // Click to upload: manually upload to the server, this will trigger the component's http-request

    submitUpload() {

      if (this.is_type && this.fileList) {

        // this.$refs.upload.submit()

        // console.log(this.formData)

        importData(this.formData).then((data) => {

          if (data.code == 200) {

            this.msgSuccess('success')

            this.fileList = []//Clear the uploaded file display list

            this.is_type = ''

          this.$refs.upload.clearFiles()//Clear the list of uploaded files (this method does not support calling in before-upload)

          } else {

            this.msgError(data.msg)

          }

        })

      } else if (this.is_type && this.fileList.length == 0) {

        this.msgError('Please select upload file')

      } else if (!this.is_type && this.fileList.length != 0) {

        this.msgError('Please select the import mode')

      } else if (!this.is_type && this.fileList.length == 0) {

        this.msgError('Please select the import mode and upload file')

      }

    },

    // remove the selected file

    fileRemove(file, fileList) {

      if (fileList.length < 1) {

        this.uploadDisabled = true //The upload button is disabled if no file is selected

      }

    },

    // Cancel

    closeDialog() {

      this.$refs.upload.clearFiles() //clear upload file object

      this.fileList = [] //Clear the selected file list

      this.$emit('close', false)

    },

    // file changed

    fileChange(file, fileList) {

      // if (fileList.length > 0) {

      // this.fileList = [fileList[fileList.length - 1]] // Display the last selected file

      // }

      // console.log(file)

      this.formData = {

        Name: file.name,

        IsType: this.is_type,

      }

      let files = { 0: file.raw }

      this.readExcel(files)

    },

    // Import to read documents with XLSX

    readExcel(files) {

      var that = this

      // if there is no filename

      if (files.length <= 0) {

        return false

      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {

        this.$Message.error('The upload format is incorrect, please upload xls or xlsx format')

        return false

      }

      const fileReader = new FileReader()

      fileReader.onload = (ev) => {

        try {

          const data = ev.target.result

          const workbook = XLSX.read(data, {

            type: 'binary',

          })

          // get the first table

          const wsname = workbook.SheetNames[0] //

          // generate

          // table content

          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])

          console.log(ws, 'ws is the data in the table, and it is in json format')

          let list = ws.map((item) => {

            return {

              Coding: (item. material code)+'',

              Name: (item. material name)+'',

              Specification: (item. specification model)+'',

              Units: (item.Unit of measure)+'',

              AllName: (item. full name)+'',

              ApplyNumber: (item. number of applications),

              AdjustNumber: (item. adjusted quantity),

              Remark: (item.Remark)+'',

            }

          })

          this.formData.BizMaterialSon = list

          // rewrite data

          this.$refs.upload.value = ''

        } catch (e) {

          return false

        }

      }

      fileReader.readAsBinaryString(files[0])

    },

  },

}

</script>

css: mixed with some other code

<style scoped lang="scss">

.title {

  text-align: center;

  font-size: 70px;

  font-weight: 600;

}

.believer {

  width: 450px;

  margin: 20px auto;

}

.select {

  position: relative;

}

.selectright {

  width: 450px;

  margin: 20px auto;

}

.selectLeft {

  width: 410px;

  position: absolute;

  left: 54%;

  top: 0;

}

.upload-demo {

  width: 100%;

}

.upImg {

  width: 150px;

  // height: 100px;

  margin: 10px auto;

}

</style>

<style scoped>

.upload-demo >>> .el-upload-dragger {

  border: none;

  height: 250px !important;

  width: 100%;

}

.box-card >>> .el-upload-dragger {

  border: none;

  height: 208px !important;

  width: 100%;

}

.el-card.is-always-shadow {

  -webkit-box-shadow: 0 2px 12px 0 #f0f0f0;

  box-shadow: 0px -6px 20px 0 #f0f0f0;

  border: none;

}

.box-card >>> .el-upload {

  display: block !important;

}

.buttonUp {

  display: block;

  width: 140px;

  padding: 15px;

  border-radius: 5px;

  margin: 0px auto;

  margin-bottom: 10px;

}

.el-upload__type {

  text-align: center;

  color: #a7a3a2;

  padding: 20px;

  box-shadow: 0px 4px 14px 0px #f0f0f0;

  margin-top: 0px;

}

</style>

Integration: The code in an entire page can be copied and modified by yourself

<template>

  <div class="app-container home">

    <div style="padding-top: 30px">

      <div class="title">Upload excel to import material purchase order</div>

      <div class="select">

        <div class="selectright">

          <el-form>

            <el-form-item label="import mode">

              <el-select v-model="is_type" placeholder="Please enter the import model">

                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>

              </el-select>

            </el-form-item>

          </el-form>

        </div>

        <div class="selectLeft">

          <span style="color: red">*</span>

          The package can be packaged as a whole package, loose package, or single source; if it is a whole package, you cannot fill in 0 when filling in the price, and each item is required; if it is a loose package, you can fill in 0 for the price.

        </div>

      </div>

      <div class="crenter">

        <div>

          <el-card class="box-card">

            <el-upload

              ref="upload"

              accept=".xls,.xlsx"

              action="#"

              :auto-upload="false"

              :multiple="false"

              :file-list="fileList"

              :before-upload="beforeUpload"

              :http-request="uploadHttpRequest"

              :on-remove="fileRemove"

              :on-change="fileChange"

              drag

            >

              <img class="upImg" src="../../style/img/up.png" alt="" />

              <el-button class="buttonUp" type="primary">上传excel</el-button>

              <div class="el-upload__text">Or drag and drop a file</div>

            </el-upload>

          </el-card>

          <div class="el-upload__tip">Only upload excel files, and no more than 500kb</div>

        </div>

        <div><el-button style="width: 450px; margin: 20px auto; padding: 15px" type="primary" @click="submitUpload">确认上传</el-button></div>

      </div>

    </div>

  </div>

</template>

<script>

import request from '@/utils/request'

import { getToken } from '@/utils/auth'

import { importData } from '@/api/purchase/purchase'

import XLSX from '../../../node_modules/xlsx'

export default {

  data() {

    return {

      options: [

        {

          value: 1,

          label: 'whole package',

        },

        {

          value: 2,

          label: 'loose package',

        },

        {

          value: 3,

          label: 'single source',

        },

      ],

      is_type: '',

      action: process.env.VUE_APP_BASE_API + '/business/BizMaterialSum/importData',

      // user import parameters

      fileList: [],

      // read

      defaultIndex: 0, // display the first worksheet by default

      wb: null, // worksheet object

      formData: {},

    }

  },

  created() {},

  methods: {

    beforeUpload(file) {

      //file type

      const isType = file.type === 'application/vnd.ms-excel'

      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      const fileType = isType || isTypeComputer

      if (!fileType) {

        this.$message.error('Upload files can only be in xls/xlsx format!')

      }

      // The file size is limited to 10M

      const fileLimit = file.size / 1024 / 1024 < 10

      if (!fileLimit) {

        this.$message.error('The uploaded file size does not exceed 10M!')

      }

      return fileType && fileLimit

    },

    // Customize the upload method, param is the default parameter, you can get the file information, the specific information is as follows

    uploadHttpRequest(param) {

      // const formData = new FormData() //FormData object, adding parameters can only be added in the form of append('key', value)

      // formData.append('file', param.file) //Add file object

      // formData.append('uploadType', this.is_type) //Parameters to be passed by the interface

      // // call interface api

      // importData(formData).then((data) => {

      //   if (data.code == 200) {

      // this.msgSuccess('success')

      // param.onSuccess() // Successfully uploaded files display a green tick

      //     this.fileList = []

      //     this.is_type = ''

      //   } else {

      //     this.msgError(data.msg)

      //   }

      // })

    },

    // Click to upload: manually upload to the server, this will trigger the component's http-request

    submitUpload() {

      if (this.is_type && this.fileList) {

        // this.$refs.upload.submit()

        // console.log(this.formData)

        importData(this.formData).then((data) => {

          if (data.code == 200) {

            this.msgSuccess('success')

            this.fileList = []//Clear the uploaded file display list

            this.is_type = ''

          this.$refs.upload.clearFiles()//Clear the list of uploaded files (this method does not support calling in before-upload)

          } else {

            this.msgError(data.msg)

          }

        })

      } else if (this.is_type && this.fileList.length == 0) {

        this.msgError('Please select upload file')

      } else if (!this.is_type && this.fileList.length != 0) {

        this.msgError('Please select the import mode')

      } else if (!this.is_type && this.fileList.length == 0) {

        this.msgError('Please select the import mode and upload file')

      }

    },

    // remove the selected file

    fileRemove(file, fileList) {

      if (fileList.length < 1) {

        this.uploadDisabled = true //The upload button is disabled if no file is selected

      }

    },

    // Cancel

    closeDialog() {

      this.$refs.upload.clearFiles() //clear upload file object

      this.fileList = [] //Clear the selected file list

      this.$emit('close', false)

    },

    // file changed

    fileChange(file, fileList) {

      // if (fileList.length > 0) {

      // this.fileList = [fileList[fileList.length - 1]] // Display the last selected file

      // }

      // console.log(file)

      this.formData = {

        Name: file.name,

        IsType: this.is_type,

      }

      let files = { 0: file.raw }

      this.readExcel(files)

    },

    // Import to read documents with XLSX

    readExcel(files) {

      var that = this

      // if there is no filename

      if (files.length <= 0) {

        return false

      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {

        this.$Message.error('The upload format is incorrect, please upload xls or xlsx format')

        return false

      }

      const fileReader = new FileReader()

      fileReader.onload = (ev) => {

        try {

          const data = ev.target.result

          const workbook = XLSX.read(data, {

            type: 'binary',

          })

          // get the first table

          const wsname = workbook.SheetNames[0] //

          // generate

          // table content

          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])

          console.log(ws, 'ws is the data in the table, and it is in json format')

          let list = ws.map((item) => {

            return {

              Coding: (item. material code)+'',

              Name: (item. material name)+'',

              Specification: (item. specification model)+'',

              Units: (item.Unit of measure)+'',

              AllName: (item. full name)+'',

              ApplyNumber: (item. number of applications),

              AdjustNumber: (item. adjusted quantity),

              Remark: (item.Remark)+'',

            }

          })

          this.formData.BizMaterialSon = list

          // rewrite data

          this.$refs.upload.value = ''

        } catch (e) {

          return false

        }

      }

      fileReader.readAsBinaryString(files[0])

    },

  },

}

</script>

<style scoped lang="scss">

.title {

  text-align: center;

  font-size: 70px;

  font-weight: 600;

}

.believer {

  width: 450px;

  margin: 20px auto;

}

.select {

  position: relative;

}

.selectright {

  width: 450px;

  margin: 20px auto;

}

.selectLeft {

  width: 410px;

  position: absolute;

  left: 54%;

  top: 0;

}

.upload-demo {

  width: 100%;

}

.upImg {

  width: 150px;

  // height: 100px;

  margin: 10px auto;

}

</style>

<style scoped>

.upload-demo >>> .el-upload-dragger {

  border: none;

  height: 250px !important;

  width: 100%;

}

.box-card >>> .el-upload-dragger {

  border: none;

  height: 208px !important;

  width: 100%;

}

.el-card.is-always-shadow {

  -webkit-box-shadow: 0 2px 12px 0 #f0f0f0;

  box-shadow: 0px -6px 20px 0 #f0f0f0;

  border: none;

}

.box-card >>> .el-upload {

  display: block !important;

}

.buttonUp {

  display: block;

  width: 140px;

  padding: 15px;

  border-radius: 5px;

  margin: 0px auto;

  margin-bottom: 10px;

}

.el-upload__type {

  text-align: center;

  color: #a7a3a2;

  padding: 20px;

  box-shadow: 0px 4px 14px 0px #f0f0f0;

  margin-top: 0px;

}

</style>

Page image:

 

Guess you like

Origin blog.csdn.net/weixin_51426266/article/details/125312184