从指定路径的Excel文件中读取数据,跳过第一行(通常为标题行),并将每一行的数据映射到实体类对象的属性中。终极,将所有数据网络到列表中。
1、实体类代码
- package com.code.boot.model;
- import lombok.Data;
- /**
- * @Author: Gurucyy
- * @date: 2024/03/23 09:47:05
- * @Description: EntityDto
- */
- @Data
- public class EntityDto {
- private String companyName; //企业名称
- private String plate; // 板块
- private String industry; // 行业
- private String companyCode; // 统一社会信用代码
- }
复制代码 2、实现方法
- package com.code.boot.controller;
- import org.apache.poi.ss.usermodel.*;
- import java.io.FileInputStream;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- public class ExcelReader {
- // 从指定的Excel文件路径读取数据,并返回一个SuzhouDto列表
- private List<EntityDto> readExcelData(String excelFilePath) {
- List<EntityDto> entityDtosList = new ArrayList<>();
- try (FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
- Workbook workbook = WorkbookFactory.create(fileInputStream)) {
- Sheet sheet = workbook.getSheetAt(0);
- boolean isFirstRow = true;
- for (Row row : sheet) {
- if (isFirstRow) {
- isFirstRow = false;
- continue; // 跳过第一行(标题行)
- }
- EntityDto entityDto = new EntityDto();
- entityDto.setCompanyName(getCellValue(row.getCell(0)));
- entityDto.setPlate(getCellValue(row.getCell(1)));
- entityDto.setIndustry(getCellValue(row.getCell(2)));
- entityDto.setCompanyCode(getCellValue(row.getCell(3)));
- entityDtosList.add(entityDto);
- }
- } catch (Exception e) {
- // 根据自己需求,实现自定义异常处理机制
- e.printStackTrace();
- }
- return entityDtosList;
- }
- // 根据单元格类型获取单元格的值
- private String getCellValue(Cell cell) {
- if (cell == null) {
- return "";
- }
- switch (cell.getCellType()) {
- case STRING:
- return cell.getStringCellValue();
- case NUMERIC:
- if (DateUtil.isCellDateFormatted(cell)) {
- // 可选:将日期转换为格式化的日期字符串
- return cell.getDateCellValue().toString();
- } else {
- return Double.toString(cell.getNumericCellValue());
- }
- case BOOLEAN:
- return Boolean.toString(cell.getBooleanCellValue());
- case FORMULA:
- return cell.getCellFormula();
- default:
- return ""; // 对于空白和其他类型
- }
- }
- // todo 如果想将所有类型的单元格统一转换为字符串类型,注释掉上面的getCellValue方法,调用该方法即可
- //private String getCellValue(Cell cell) {
- // if (cell == null) {
- // return "";
- // }
- // cell.setCellType(CellType.STRING);
- // return cell.getStringCellValue();
- //}
- }
复制代码 3、根据终极返回的entityDtosList列表,使用MyBatisPlus的批量插入方法或其他方法,将数据保存到数据库。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |