vue学习(五)el-upload 组件自动上传

demo直接提交类型:data带参数


<el-table-column
            label="数据"
            align="center"
            prop="data">
            <template slot-scope="scope">
              <el-upload
                ref="upload"
                :on-success="handleSuccess"//成功回调
                :on-error="handleError"//失败回调
                :before-upload="beforeUpload"//上传之前检验
                :auto-upload="true"
                :data="{cid:scope.row.id}"//传给后台的额外参数从此处是从
                action="/api/car/uploadExcel"
                class="upload-demo">
                <el-button
                  slot="trigger"
                  size="mini"
                  type="success">选择文档</el-button>
              </el-upload>
            </template>
 </el-table-column>
data() {
    return {
      fileList: []
    }
},  
methods: {
    handleError(res, file, fileList) { // 文件上传失败处理
      this.$notify.success({
        title: '失败',
        message: `文件上传失败`
      })
      this.$refs.upload.clearFiles()
    },
    handleSuccess(res, file, fileList) { // 文件上传成功处理
      this.$notify.success({
        title: '成功',
        message: `文件上传成功`
      })
      this.$refs.upload.clearFiles()
      //成功后的业务逻辑处理
    },
    beforeUpload(file) {//上传前检验
      if (!file) {
        return false
      } 
      console.log(file)
      if (/xlsx$/.test(file.name)) {
        console.log('格式正确')
        return true
      } else {
        console.log('格式错误')

        this.$message.error('请选择正确的文件上传')
        this.$refs.upload.clearFiles()
        return false
      }
    }
}

后台接参数:

  @RequestMapping(value = "/car/uploadExcel" ,method = RequestMethod.POST)
    @ResponseBody
    public Object uploadExcel(MultipartFile file, @RequestParam("cid") String cid, HttpServletRequest request) throws IOException {
        loggerFile.info("上传excel接口-----------开始" );
        loggerFile.info(cid );//这是传进来的额外的参数

        //1.获取信息
        //2.解析xlsx
        //3.插入数据库
     HashMap<String, Object> returnMap = new HashMap<String, Object>();
     
 if (file != null){
            String name = file.getOriginalFilename();
            if (name.endsWith("xlsx")) {
                //TODO excel解析 逻辑,通过excelFile.getInputStream(),处理Excel文件

                int result= 0;
                InputStream inputStream = null;
                List<List<Object>> listResult = null;
                inputStream = file.getInputStream();
                try {
                    listResult = new POIExcelUtil().getBankListByExcel(inputStream, file.getOriginalFilename());
                    //TODO 业务逻辑,循环添加
                    if (CollectionUtils.isEmpty(listResult)) {
                        returnMap.put("code","00");
                        returnMap.put("msg","文档空数据");
                    }

                    //自己的业务处理
                    //xxxxxxxxxxxxxxxxxxxxxxx

                    loggerFile.info("上传excel接口-----------操作结果"+result );
                } catch (Exception e) {
                    e.printStackTrace();
                }
                inputStream.close();

                if (result>0){
                    returnMap.put("code","00");
                    returnMap.put("num",result);
                    returnMap.put("msg","成功"+result+"条数据");
                }
            }else {
                returnMap.put("code","99");
                returnMap.put("msg","文件格式错误");
            }
        }else{
            returnMap.put("code","99");
            returnMap.put("msg","文件格式错误");
        }
        loggerFile.info("上传excel接口-----------结束" );

     return returnMap;
}

excel解析工具类

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
    </dependencies>
public class POIExcelUtil {

    private final static String excel2003L = ".xls"; // 03- 版本的excel
    private final static String excel2007U = ".xlsx"; // 07+ 版本的excel

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     *
     * @param inputStream,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inputStream, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inputStream); // 2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inputStream); // 2007+
        } else {
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     *
     * @param inputStream,fileName
     * @return
     * @throws IOException
     */
    public List<List<Object>> getBankListByExcel(InputStream inputStream, String fileName) throws Exception {
        List<List<Object>> list = null;

        // 创建Excel工作薄
        Workbook work = this.getWorkbook(inputStream, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        // 遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            // 遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                // 跳过空行和标题行
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                // 遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                    cell = row.getCell(k);
                    if (cell == null) {
                        li.add("");
                        continue;
                    }

                    li.add(this.getCellValue(cell));
                }
                list.add(li);
            }
        }
        System.out.println(list);
        return list;

    }

    /**
     * 描述:对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }

}

猜你喜欢

转载自blog.csdn.net/jack_bob/article/details/104550850