上一篇写了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>