您好,欢迎访问一九零五行业门户网

Java如何将Excel数据导入数据库

1、根据业务需求设计数据库表
2、根据数据库表设计一个excel模板模板的每列属性必须与表字段一一对应
3、环境准备我这里项目环境是基于springboot单体式架构,持久层用的公司框架,内置了基于mybatis-plus的各种单表操作的方法。
导入依赖
<!--使用poi读取文件--> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version>3.17</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml</artifactid> <version>3.17</version> </dependency>
4、通过插件生成表对应的实体类/** * tbzbzs: 值班值守表 * @author zs * @date 2021-12-17 08:46:31 **/@data@apimodel(value="值班值守表,对应表tb_zbzs",description="适用于新增和修改页面传参")public class tbzbzs extends probaseentity<tbzbzs> { private static final long serialversionuid = 1l; @apimodelproperty(value="id") private string id; // id @apimodelproperty(value="部门") private string bm; // 部门 @apimodelproperty(value="值班上报") private string zbsb; // 值班上报 @apimodelproperty(value="值班人员") private string zbry; // 值班人员 @apimodelproperty(value="上报时间") @datetimeformat(pattern = "yyyy-mm-dd hh:mm:ss") private java.util.date sbsj; // 上报时间 @apimodelproperty(value="结束时间") @datetimeformat(pattern = "yyyy-mm-dd hh:mm:ss") private java.util.date jssj; // 结束时间 @apimodelproperty(value="联系方式") private string lxfs; // 联系方式 @apimodelproperty(value="状态") private string zt; // 状态 /** * 逻辑删除 */ @apimodelproperty(value="逻辑删除") private string delflag; /** * 创建时间 */ @apimodelproperty(value="创建时间") @datetimeformat(pattern = "yyyy-mm-dd hh:mm:ss") private date createdate;}
5、自定义编写工具类这里提供的是一个基础模板,根据业务的需求可以增加转换条件
import org.apache.poi.hssf.usermodel.hssfworkbook;import org.apache.poi.ss.usermodel.cell;import org.apache.poi.ss.usermodel.row;import org.apache.poi.ss.usermodel.sheet;import org.apache.poi.ss.usermodel.workbook;import org.apache.poi.xssf.usermodel.xssfworkbook;import java.io.ioexception;import java.io.inputstream;import java.text.decimalformat;import java.text.simpledateformat;import java.util.arraylist;import java.util.list;/** * 新增值班排班表导入excel表工具类 * zyw */public class importexcelutil { private final static string excel2003l =".xls"; //2003- 版本的excel private final static string excel2007u =".xlsx"; //2007+ 版本的excel /** * 描述:获取io流中的数据,组装成list<list<object>>对象 * @param in,filename * @return * @throws exception */ public static list<list<object>> getlistbyexcel(inputstream in, string filename) throws exception { list<list<object>> list = null; //创建excel工作薄 workbook work = importexcelutil.getworkbook(in,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()+1; j++) { row = sheet.getrow(j); if(row==null||row.getfirstcellnum()==j){continue;} //遍历所有的列 list<object> li = new arraylist<object>(); for (int y = row.getfirstcellnum(); y < row.getlastcellnum(); y++) { cell = row.getcell(y); li.add(importexcelutil.getcellvalue(cell)); } list.add(li); } }// work.close(); return list; } /** * 描述:根据文件后缀,自适应上传文件的版本 * @param instr,filename * @return * @throws exception */ public static workbook getworkbook(inputstream instr, string filename) throws exception{ workbook wb = null; string filetype = filename.substring(filename.lastindexof(".")); if(excel2003l.equals(filetype)){ wb = new hssfworkbook(instr); //2003- }else if(excel2007u.equals(filetype)){ wb = new xssfworkbook(instr); //2007+ }else{ throw new exception("解析的文件格式有误!"); } return wb; } /** * 描述:对表格中数值进行格式化 * @param cell * @return */ public static object getcellvalue(cell cell){ object value = null; decimalformat df = new decimalformat("0"); //格式化number string字符 simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");// simpledateformat sdf = new simpledateformat("yyy-mm-dd"); //日期格式化// decimalformat df2 = new decimalformat("0.00"); //格式化数字 if (cell!=null){ 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 = sdf.format(cell.getdatecellvalue()); } break; case cell.cell_type_boolean: value = cell.getbooleancellvalue(); break; case cell.cell_type_blank: value = ""; break; default: break; } } return value; }}
6、编写具体业务逻辑service主要思想:通过工具类将excel文件解析成object泛型的集合,再将集合循环遍历,在遍历中,将每行数据一次填入对象中,再每次循环中,将赋值后的对象存入一个list集合,最后统一将集合执行批量上传的方法,存入数据库。
public map<string,object> importtprkxx(multipartfile file){ map<string,object> resultmap = new hashmap<>(); simpledateformat simpledateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss"); list<tbzbzs> tbzbzslist = new arraylist<>(); try { //获取数据 list<list<object>> olist = importexcelutil.getlistbyexcel(file.getinputstream(), file.getoriginalfilename()); resultmap.put("导入成功",200); //封装数据 for (int i = 0; i < olist.size(); i++) { list<object> list = olist.get(i); if (list.get(0) == "" || ("序号").equals(list.get(0))) { continue; } tbzbzs tbzbzs = new tbzbzs(); tbzbzs.setid(uuid.randomuuid().tostring().replace("-", "").substring(0, 20)); //根据下标获取每一行的每一条数据 if (string.valueof(list.get(0))==null) { resultmap.put("state", "部门不能为空"); continue; } tbzbzs.setbm(string.valueof(list.get(0))); if (string.valueof(list.get(1))==null) { resultmap.put("state", "值班上报不能为空"); continue; } tbzbzs.setzbsb(string.valueof(list.get(1))); if (string.valueof(list.get(2))==null) { resultmap.put("state", "值班人员不能为空"); continue; } tbzbzs.setzbry(string.valueof(list.get(2))); if (string.valueof(list.get(3))==null) { resultmap.put("state", "导入失败,上报时间不能为空"); continue; } string datestr3 = string.valueof(list.get(3)); date date3 = simpledateformat.parse(datestr3); tbzbzs.setsbsj(date3); if (string.valueof(list.get(4))==null) { resultmap.put("state", "导入失败,结束时间不能为空"); continue; } string datestr4 = string.valueof(list.get(4)); date date4 = simpledateformat.parse(datestr4); tbzbzs.setjssj(date4); if (string.valueof(list.get(5))==null) { resultmap.put("state", "联系方式不能为空"); continue; } tbzbzs.setlxfs(string.valueof(list.get(5))); if (string.valueof(list.get(6))==null) { resultmap.put("state", "状态不能为空"); continue; } tbzbzs.setzt(string.valueof(list.get(6))); if (string.valueof(list.get(7))==null) { resultmap.put("state", "逻辑删除不能为空"); continue; } tbzbzs.setdelflag(string.valueof(list.get(7))); if (string.valueof(list.get(8))==null) { resultmap.put("state", "导入失败,创建时间不能为空"); continue; } string datestr8 = string.valueof(list.get(8)); date date8 = simpledateformat.parse(datestr8); tbzbzs.setcreatedate(date8); tbzbzslist.add(tbzbzs); } int i = tbzbzsdao.inserttbzbzslist(tbzbzslist); if (i != 0) { resultmap.put("state", "导入成功"); }else { resultmap.put("state", "导入失败"); } } catch (exception e) { e.printstacktrace(); resultmap.put("state", "导入失败"); } return resultmap; }
7、在dao层对应的xml文件中,编写批量上传的方法<insert id="inserttbzbzslist" parametertype="java.util.list"> insert into tb_zbzs ( id, bm, zbsb, zbry, sbsj, jssj, lxfs, zt, del_flag, create_date ) values <foreach collection="list" item="item" separator=","> ( #{item.id}, #{item.bm}, #{item.zbsb}, #{item.zbry}, #{item.sbsj}, #{item.jssj}, #{item.lxfs}, #{item.zt}, #{item.delflag}, #{item.createdate} ) </foreach> </insert>
8、controller实现业务的控制 /** * @方法名称: excelprotbzbzs * @实现功能: 导入值班值守表excel todo: 方法入参根据页面对象设置 * @param file * @return java.lang.string * @create by zyw at 2022-03-17 16:49:31 **/ @apioperation(value="导入值班值守表excel",notes="返回导入情况接口",response = tbzbzs.class) @postmapping(value = "/excelprotbzbzs") public string excelprotbzbzs(@requestparam("file") multipartfile file){ try { return buildresultstr(service.importtprkxx(file).get("state").equals("导入成功") ? buildsuccessresultdata() : builderrorresultdata(service.importtprkxx(file).get("state").tostring())); }catch (runtimeexception e){ logerror(log, e); return buildresultstr(builderrorresultdata(e)); } }
9、通过swagger测试接口
10、在数据和控制台中查看导入效果
以上就是java如何将excel数据导入数据库的详细内容。
其它类似信息

推荐信息