欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue.js实现excel和图片的导入

程序员文章站 2022-06-06 19:55:59
...

由于项目需要同时导入excel文档和jpg图片,因此尝试了一些方法来完成任务。

图片数据是以base64格式存入的,显示和转移都比较方便。

一开始考虑的是将图片插入excel中,这样的好处是一一对应,不会出错,但是搜索了关于图片的插入,还是比较复杂的,对用户来说不太现实。

最后我将excel和图片分开导入,使用图片名来对应字段,效果还可以,下面附上代码。
下面是数据的导入:

	<el-form-item label="选择excel文件">
				<el-upload
				:action="uploadUrl"
        v-loading="loading"
        :on-change="handleChange"
        :on-remove="handleRemove"	
        :limit="1"
        accept=".xls,.xlsx"	     
				:default-file-list="fileList"
        :before-upload="beforeAvatarUpload">
					<i class="el-icon-upload"></i>
					<div class="el-dragger__text">点击文件进行上传</div>
					<div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件</div>
				</el-upload>
	</el-form-item>
	<el-form-item>
	<el-button type="primary" @click="addlist()" :loading="isLoading">导入</el-button>
         <el-button @click="goback()">返回</el-button>
			</el-form-item>

使用的是element-ui,使用的是vue解析excel方法,需要安装xslx,可参考https://blog.csdn.net/qq_32563571/article/details/83149929

下面是方法:

  export default {
    data() {
      
      return {
        isLoading: false,
        fileList: [],
        
        // fileTemp:null,
        form: {       
        },
        uploadUrl: '',
        rules: {
        }
      }
    },
    methods: {
    handleRemove(file,fileList){
        this.file = null
    },

      handleChange(file, fileList){
      const fileReader = new FileReader();
      
      	fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });
          // console.log(workbook)
          let sheet = Object.keys(workbook.Sheets)[0];
          var array = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);  //获得以第一列为键名的sheet数组对象
          var arrayStr = JSON.stringify(array)
          .replace(/学号/g,"sid")
          .replace(/姓名/g,"name")
          .replace(/性别/g,"sex")
          .replace(/身份证号/g,"idnumber")
          .replace(/学院名称/g,"academy")
          .replace(/专业名称/g,"major")
          array = JSON.parse(arrayStr);
          // console.log(array)
          this.form = array
          } catch (e) {
            console.log(e)
          }
        };
        fileReader.readAsBinaryString(file.raw);

        },
      addlist(form) {
            this.isLoading = !this.isLoading
            this.apiPost('admin/degree/addList', this.form).then((res) => {
              this.handelResponse(res, (data) => {
                _g.toastMsg('success', data)
                setTimeout(() => {
                  this.goback()
                }, 1500)
              }, () => {
                this.isLoading = !this.isLoading
              })
            })
      },

    },
     created() {
      this.uploadUrl = window.HOST
       _g.closeGlobalLoading()
    },

这里使用了json字符串转化,将头标题汉字转化为数据表字段名来进行添加。

后台用的是ThinkPhp方法,接收到数组进行循环添加即可,然后返回data,显示成功和覆盖的条目数,这里就不列举了。

插入数据后,接下来是图片的导入:

<el-upload
                  ref="upload"
                  v-loading="loading"
                  :action="uploadurl"
                  :auto-upload="false"
                  :multiple="true"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :with-credentials="true"
                  accept = ".jpg,"
                  :before-upload="beforeAvatarUpload">
  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">点击文件进行上传</div>
              <div class= "el-upload__tip" slot="tip">只能上传jpg文件,可进行批量选择</div>
</el-upload>

              	<el-form-item>
				<el-button type="primary" @click="addimg()" :loading="isLoading">导入</el-button>
        <el-button @click="goback()">返回</el-button>

可一次导入多张图片,图片名对应每个学生的身份证号(多张图片可用加后缀进行表示)。

export default {
    data() {
      return {
        isLoading: false,
        fileList: [],
        uploadurl:'',
        // ExcelDate:[],
        // fileTemp:null,
        form: [],
        uploadUrl: '',
        rules: {
        }
      }
    },
    methods: {
    handleRemove(file,fileList){
      this.handleChange(file,fileList);
    },
    handleChange (file, fileList) {
      // console.log(fileList);
      var files = [];
      for (let index = 0; index < fileList.length; index++) {
        const element = fileList[index];
      // console.log(element.name);
      // var index=element.name.lastIndexOf('.');
      // var tmp= element.name.substring(0,index)

        this.getBase64(element.raw).then(res => {
          files.push({"name":element.name,"base64data":res});
        })
      }
      this.form = files;

    },
      //将图片转为base64 加上 name属性赋值给数组,发送到后台
      getBase64 (file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader()
          let imgResult = ''
          reader.readAsDataURL(file)
          reader.onload = function () {
            imgResult = reader.result        
          }
          reader.onerror = function (error) {
            reject(error)
          }
          reader.onloadend = function () {
            resolve(imgResult)
          }
        })
      },

       beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt3M = file.size / 1024 / 1024 < 3;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt3M) {
          this.$message.error('上传头像图片大小不能超过 3MB!');
        }
        return isJPG && isLt3M;
      },
        
      addimg() {
            this.isLoading = !this.isLoading
            this.apiPost('admin/degree/addimg', this.form).then((res) => {
              this.handelResponse(res, (data) => {
                _g.toastMsg('success', data)
                setTimeout(() => {
                  this.goback()
                }, 1500)
              }, () => {
                this.isLoading = !this.isLoading
              })
            })
      },

    },
     created() {
      this.uploadUrl = window.HOST
       _g.closeGlobalLoading()
    },

上面的操作包括base64转化和创建数组,将图片名、bas64图片发送给后台进行接收。

然后后台更新一下,就完成了。

 

相关标签: vue.js php mysql