java批量讀取Excel文件中數據導入進mysql數據庫中---(通過java方式)


1.Excel中有兩條數據,我們需要通過java利用IO流操作,把這兩條數據,導入進我們的mysql數據庫。

 

 

 

 

 

 

2.在pom.xml 中導入POI依賴

<!--excel文件提取 poi框架依賴-->
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.9</version>
</dependency>

 

3.在model中建立實體類,與Excel中的表頭一致----------實體類

@Data
@ApiModel("java批量導入")
@Table(name = "excel")
public class ExcelModel {

    @Id
    @Column(name = "id")
    @GeneratedValue(generator="JDBC")
    @ApiModelProperty("主鍵")
    private Integer id;
    @ApiModelProperty("公司名字")
    private String companyName;
    @ApiModelProperty("職位名稱")
    private String jobTitle;
    @ApiModelProperty("年薪")
    private String annualSalary;
    @ApiModelProperty("候選人姓名")
    private String name;

    public void toPo(ExcelModelFormBean formBean) {

        this.id = formBean.getId();
        this.companyName = formBean.getCompanyName();
        this.jobTitle = formBean.getJobTitle();
        this.annualSalary = formBean.getAnnualSalary();
        this.name = formBean.getName();
    }
}

 

4.通過IO流批量獲取Excel中的信息轉化成list集合-------工具類

    /**
     * 批量獲取excel文件中的信息轉換成list集合
     *
     * @param file 文件信息
     * @return list集合
     */
    public static List<ExcelDateInfo> getExcelFile(MultipartFile file) throws IOException {

        List<ExcelDateInfo> list = new LinkedList<>();

        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return Collections.emptyList();
        }
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return Collections.emptyList();
        } else {
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }

            InputStream is = file.getInputStream();
            Workbook workbook;
            if (isExcel2003) {
                workbook = new HSSFWorkbook(is);
            } else {
                workbook = new XSSFWorkbook(is);
            }
            Sheet sheet = workbook.getSheetAt(0);
            if (null == sheet) {
                return Collections.emptyList();
            }
            //r = 1 表示從第二行開始循環 如果你的第三行開始是數據
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                //通過sheet表單對象得到 行對象
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                ExcelDateInfo info = new ExcelDateInfo();
                if (row.getCell(0) != null) {
                    //得到每一行第二個單元格的值
                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                    info.setColumn1(row.getCell(0).getStringCellValue());
                }
                if (row.getCell(1) != null) {
                    //得到每一行的 第三個單元格的值
                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                    info.setColumn2(row.getCell(1).getStringCellValue());
                }
                if (row.getCell(2) != null) {
                    row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                    info.setColumn3(row.getCell(2).getStringCellValue());
                }
                if (row.getCell(3) != null) {
                    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                    info.setColumn4(row.getCell(3).getStringCellValue());
                }
                // 對象放入集合
                list.add(info);
            }
        }
        return list;
    }

 

5.調用sql批量添加到數據庫中

    /**
     * 模板文件--批量添加
     *
     * @param file 添加信息
     * @return 添加個數
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Integer> saveOrderList(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return new Result<>(Result.Status.INVALID_PARAM);
        }
        if (StringUtils.equals(fileName.substring(fileName.lastIndexOf(".")), "xlsx")) {
            return new Result<>(Result.Status.INVALID_PARAM);
        }

        try {
            //讀取Excel文件轉化成list
            List<ExcelDateInfo> list = FileUtil.getExcelFile(file);
            if (CollectionUtils.isEmpty(list) || list.size() < 2) {
                return new Result<>(Result.Status.EMPTY_DATA);
            }

            ExcelDateInfo excel = list.get(0);
            // 驗證文件頭是否正確
            if (!"公司".equals(excel.getColumn1()) || !"職位".equals(excel.getColumn2()) ||
                    !"年薪".equals(excel.getColumn3()) || !"姓名".equals(excel.getColumn4())) {
                return new Result<>(Result.Status.TEMPLATE_ERROR);
            } else {
                list.remove(0);
            }

            List<ServiceHistoryOrder> orderList = new ArrayList<>();
            for (ExcelDateInfo info : list) {
                if (StringUtils.isEmpty(info.getColumn1()) && StringUtils.isEmpty(info.getColumn2()) &&
                        StringUtils.isEmpty(info.getColumn3()) && StringUtils.isEmpty(info.getColumn4())) {
                    continue;
                }

                ServiceHistoryOrder order = new ServiceHistoryOrder();
                // 判斷公司列長度
                if (StringUtils.isEmpty(info.getColumn1())) {
                    return new Result<>(Result.Status.EMPTY_DATA);
                } else if (info.getColumn1().length() > 500) {
                    return new Result<>(Result.Status.DATA_TOO_LONG);
                } else {
                    order.setCompanyName(info.getColumn1());
                }
                // 判斷職位列長度
                if (StringUtils.isEmpty(info.getColumn2())) {
                    return new Result<>(Result.Status.EMPTY_DATA);
                } else if (info.getColumn2().length() > 500) {
                    return new Result<>(Result.Status.DATA_TOO_LONG);
                } else {
                    order.setJobTitle(info.getColumn2());
                }
                // 判斷年薪列長度
                if (StringUtils.isEmpty(info.getColumn3())) {
                    return new Result<>(Result.Status.EMPTY_DATA);
                } else if (info.getColumn3().length() > 500) {
                    return new Result<>(Result.Status.DATA_TOO_LONG);
                } else {
                    order.setAnnualSalary(info.getColumn3());
                }
                // 判斷姓名列長度
                if (StringUtils.isEmpty(info.getColumn4())) {
                    return new Result<>(Result.Status.EMPTY_DATA);
                } else if (info.getColumn4().length() > 500) {
                    return new Result<>(Result.Status.DATA_TOO_LONG);
                } else {
                    order.setName(info.getColumn4());
                }
                orderList.add(order);
            }
            // 調用批量插入的sql語句,把excel數據插入到數據庫    返回成功條數
            int result = orderMapper.saveHistoryOrderList(orderList);
            if (result == 0) {
                return new Result<>(Result.Status.ERROR);
            }
            return new Result<>(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(Result.Status.ERROR);
        }
    }

 

6.有些Model和Mapper和Controller調用就不寫了

 

Best Regards!
Make a little progress every day!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM