Vue+Java导入excel文件解析(xlsx格式文件)

Java代码

/**
     * 导入总表数据
     */
    @PostMapping("/importGeneralTable")
    public AjaxResult importGeneralTable(@RequestBody @RequestParam("files") MultipartFile files, @RequestParam("devType") String type) {
       try {
       		//文件转换
            File file = MultipartFileConverter.convert(files);
            // 加载 Excel 文件
            FileInputStream fis = new FileInputStream(file);
            Workbook workbook = new XSSFWorkbook(fis);

            // 获取第一个工作表
            for (int c = 0; c < workbook.getNumberOfSheets(); c++) {
                Sheet sheet = workbook.getSheetAt(c);
                int lastRowNum = sheet.getLastRowNum(); // 获取最后一行的索引,这通常是工作表中的最大行数
                int lastColumnNum = 0; // 获取最后一列的索引(基于0),这通常是行中的最大列数
                for (int r = 0; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row != null) {
                        int tempLastColumnNum = row.getLastCellNum();
                        if (tempLastColumnNum > lastColumnNum) {
                            lastColumnNum = tempLastColumnNum;
                        }
                    }
                }

                if (lastRowNum == 0 || lastColumnNum == 0) {
                    continue;
                }
                // 迭代行
                for (int rowIndex = 0; rowIndex <= lastRowNum; rowIndex++) {
                    Row row = sheet.getRow(rowIndex);
                    if (row == null) {
                        // 如果行为空,则跳过
                        continue;
                    }
                    //循环列
                    for (int colIndex = 0; colIndex < lastColumnNum; colIndex++) {
                        Cell cell = row.getCell(colIndex);
                        if (cell == null) {
                            continue;
                        }
                        String contents = ExcelUtil.getCellValue(cell);
                        System.out.println(contents);
                    }
                }
            }
            // 关闭工作簿
            workbook.close();
        } catch (OLE2NotOfficeXmlFileException e){
            e.printStackTrace();
            throw new ServiceException("文件格式错误,请检查是否为xlsx", HttpStatus.WARN);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("导入文件异常,请检查文件内容格式是否正确", HttpStatus.WARN);
        }
        return AjaxResult.success();
    }

Vue代码




你可能感兴趣的:(vue.js,java,excel)