springboot excel上传并且存入oracle数据库
上一篇写了springboot 下载excel 模板,目前有个需求是把 下载的excle 填上数据 上传,并且保存的数据库,这边只针对后台操作
@transactional 事务标识
@requestmapping(value = "/upload")
@responsebody
public retdata<string> upload(httpservletrequest request) throws exception {
retdata<string> retdata = new retdata<string>();
//获取multipartrequest
multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
// 获得文件
multipartfile multipartfile = multipartrequest.getfile("file");// 与前端设置的filedataname属性值一致
workbook book = null;
list<outdatagr> demolist = new arraylist<outdatagr>();
// 判断是xls还是xlsx
try {
book = new hssfworkbook(new poifsfilesystem(multipartfile.getinputstream()));
} catch (exception ex) {
book = new xssfworkbook(multipartfile.getinputstream());
};
int numberofsheets = book.getnumberofsheets();
for (int i = 0; i < numberofsheets; i++) {
sheet sheet = book.getsheetat(i);
// 获取sheet中有多少行,遍历每一行
int physicalnumberofrows = sheet.getphysicalnumberofrows();
for (int j = 0; j < physicalnumberofrows; j++) {
if (j == 0) {
continue;// 标题行
}
outdatagr gr = new outdatagr();
row row = sheet.getrow(j);// 获得当前行数据
gr.setname(row.getcell(0).getstringcellvalue()); // 姓名
if (row.getcell(1) != null) {
row.getcell(1).setcelltype(cell.cell_type_string);//设置cell里面的数据类型
gr.setzjhm(row.getcell(1).getstringcellvalue());// 身份证号
}
if (row.getcell(2) != null) {
row.getcell(2).setcelltype(cell.cell_type_string);
string sex = row.getcell(2).getstringcellvalue();
if ("男".equals(sex)) {
gr.setsex("1"); // 性别:男
} else {
gr.setsex("2");// 性别:女
}
}
if (row.getcell(3) != null) {
row.getcell(3).setcelltype(cell.cell_type_string);
gr.setage(row.getcell(3).getstringcellvalue());// 年龄
}
gr.setid('1');
demolist.add(gr);
}
}
// 批量保存数据
outdatagrbpo.batchsave(demolist);
retdata.setretbody("添加成功");
return retdata;
}
最后吐槽下 ,因为楼主用的mybatis要批量保存到oracle 里面,网上好多都是mysql的。。没注意,试了好多,
结果发现数据库不一样,直接也贴出来吧
<!-- oracle批量保存用户,并返回每个用户插入的id -->
<insert id="batchsave" parametertype="java.util.list">
insert into gas_out_data_gr
(
id,name,sex,age,zjhm,scny,scr,type,record_id
)
<foreach collection="list" open="(" close=")" index="" item="item" separator="union all" >
select
#{item.id},#{item.name},#{item.sex},#{item.age},#{item.zjhm},
#{item.scny},#{item.scr},#{item.type},#{item.recordid}
from dual
</foreach>
</insert>