从指定路径的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的批量插入方法或其他方法,将数据保存到数据库。
到此这篇关于java读取excel文件并写入数据库的文章就介绍到这了,更多相关java读取excel文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论