java poi导入excel并解析;配合前端vue上传文件

本文详细描述了一个Java项目中,后端Controller如何处理上传的Excel文件,包括文件内容读取、数据解析以及前端使用ElementUI组件实现文件上传的界面操作。
摘要由CSDN通过智能技术生成

 一.后台代码

1.后台Controller代码方法:

  @RequestMapping("tzImport")
    @ApiOperation("导入数据并解析保存")
    public Result tzImport(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        return tzRsvrService.importFile(file);
    }

2.获取文件内容,读取excel表格数据,获取第一个sheet页的数据

    @Transactional(rollbackFor = Exception.class)
    public Result importFile(MultipartFile file)  {
        List<TzRsvrDTO> objectList = new ArrayList<>();
        try{
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            //最后一行
            int lastRowNum = sheet.getLastRowNum();
            //i=1从excel第二行开始读取
            for(int i=1;i<=lastRowNum;i++){
                TzRsvrDTO object = new TzRsvrDTO();
                Row row = sheet.getRow(i);
                //第二列
                object.setTempName(ExcelUtils.getCellValue(row.getCell(1)));
                objectList.add(object);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //自己的业务代码

        return new Result();
    }

 3.注:中间有用到单元格值类型的方法

     
   /**
     * 单元格值类型
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
    String cellValue = "";
    if (cell == null) {
        return cellValue;
    }
    // 把数字当成String来读,避免出现1读成1.0的情况
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        cell.setCellType(Cell.CELL_TYPE_STRING);
    }
    // 判断数据的类型
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC: // 数字
            cellValue = String.valueOf(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING: // 字符串
            cellValue = String.valueOf(cell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_BOOLEAN: // Boolean
            cellValue = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA: // 公式
            cellValue = String.valueOf(cell.getCellFormula());
            break;
        case Cell.CELL_TYPE_BLANK: // 空值
            cellValue = "";
            break;
        case Cell.CELL_TYPE_ERROR: // 故障
            cellValue = "非法字符";
            break;
        default:
            cellValue = "未知类型";
            break;
    }
    return cellValue;
}

二.前端代码

1.页面操作

<el-form-item>
          <el-button type="success"  @click="excelDialogVisible = true">导入</el-button>
        </el-form-item>
 <!-- 导入弹窗-->
    <el-dialog title="excel批量导入" :visible.sync="excelDialogVisible" width="50%" center>
          <el-upload
            class="upload-demo"
            :action="importUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
             multiple
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept=".xlsx,.xls"
            :auto-upload="true">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip"  class="el-upload__tip">只能上传xlsx/xls文件,且不超过5MB</div>
          </el-upload>
 
        </el-dialog>
data() {
    return {
        excelDialogVisible:false,
          uploading:false,
          importUrl:`${window.SITE_CONFIG['apiURL']}/taizhang/tzrsvr/tzImport?                
          token=${Cookies.get('token') || ''}`,
          fileList:[]
    }
}
 methods: {
        handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择        
       了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      },
      handleSuccess(response,file, fileList) {
        if(response.code != 0){
          return this.$message.error(response.msg)
        }else{
          return this.$message.success('上传成功')
        }       
      },
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值