Vue里如何导入导出Excel数据(后端Java)

首先是前端,需要用到的代码包括方法和必要的数据以及element弹框,按钮组件

以导入学生为例

导出:

点击按钮:

<el-button type="primary" @click="exportStudentExcel()">导出</el-button>

按钮单击事件:

// 导出数据
    exportStudentExcel () {
      var wb = XLSX.utils.table_to_book(document.querySelector("#user-out-table"))
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'userlist.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }

需要导入的相关第三方库:

import FileSaver from "file-saver";
import XLSX from "xlsx";

导入:

点击按钮:

<el-button type="primary" @click="importStudentExcel()">导入</el-button>

按钮单击事件:

importStudentExcel(){
      this.importDialogVisible = true;
    }

需要一个弹框组件以及控制他显示的变量:

importDialogVisible: false
<!-- 点击导入后弹出框 -->
    <el-dialog title="导入学生" v-model="importDialogVisible" width="45%">
      <input ref="file" type="file" accept=".xlsx,.xls" style="display: none;" @change="uploadFile">
      <el-button type="primary" icon="el-icon-upload" @click="clickFile">选择文件</el-button>
    </el-dialog>

选择文件事件:

clickFile() {
      this.$refs.file.dispatchEvent(new MouseEvent('click'))
    }

文件点击事件:

// 上传文件
    async uploadFile() {
      const file = this.$refs.file.files
      var extName = file[0].name.substring(file[0].name.lastIndexOf('.')).toLowerCase()
      if (extName === '.xlsx' || extName === '.xls') {
        var formData = new FormData()
        formData.append('file', file[0])
        request.post("/api/user/uploadExcel", formData).then(res => {
          if(res.code === '0') {
            this.$message({
              type: 'success',
              message: '数据导入成功!'
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        })
      }
      else {
        this.$message.error('数据导入失败,请选择正确的xlsx模板文件')
      }
      this.importDialogVisible = false;
      this.load();
    }

后台对EXCEL数据进行处理的代码:

@PostMapping("/uploadExcel")
    @ApiOperation("excel")
    public Object taskUploadExcel(@RequestParam(value = "file") MultipartFile file) throws Exception{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 判断文件格式 我需要的是EXCEL表
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        List<User> list = new ArrayList<>();
        try{
            InputStream is = file.getInputStream();
            // 版本不支持了
//            HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(is));
            // 读取工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            // 读取工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();
            User task = null;
            for (int j = 1; j < rows; j++) {
                task = new User();
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);
                System.out.println("row="+row+"++++++++++++++++++++++++++++++++++++++++++");
                row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                task.setAccount(row.getCell(1).getStringCellValue());
                task.setUsername(row.getCell(2).getStringCellValue());
                // 密码开头要为字母 不然检测失败
                task.setPassword(row.getCell(3).getStringCellValue());
                task.setSex(row.getCell(4).getStringCellValue());
                task.setCellphone(row.getCell(5).getStringCellValue());
                task.setEmail(row.getCell(6).getStringCellValue());
                task.setIdentify(row.getCell(7).getStringCellValue());

                task.setBorrowNumber((int)row.getCell(8).getNumericCellValue());
                task.setRemark(row.getCell(9).getStringCellValue());
                String stu_num = task.getAccount();
                User user1 = userMapper.getUserByAccount(stu_num);
                if(user1!=null){
                    throw new Exception("学生已存在");
                }
                userMapper.insert(task);
                list.add(task);
                System.out.println("总条数="+list.size());
                System.out.println("结束");
                System.out.println("退出循环");
                System.out.println("----------------");
            }
        }catch (Exception e){
            return Result.error("-1","导入失败:"+e.getMessage());
        }
        return Result.success();
    }

仅供参考嘞

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值