基于SpringBoot框架 导入Excel文档
前言:
关于SpringBoot中Excel文档的上传解析
提示:以下是本篇文章正文内容,下面案例可供参考
使用步骤:
1.导入jar包
代码如下(示例):
<!-- xls,xlsx文件 解析jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.编写Contriller层
代码如下(示例):
@PostMapping("/importuserinfo")
public CommonResult importUserInfo(@RequestParam("file") MultipartFile file , @RequestParam("schoolId")String schoolId , @RequestParam("areaCode")String areaCode ) {
//参数:文件,学校id,地区代码
CommonResult result = new CommonResult();//这个是我自己写的JSON传输对象
Object resultTpye = null;//结果:true,false
String fileName = file.getOriginalFilename();//获取文件名
try {
resultTpye = excelService.importUserInfo(fileName, file, schoolId, areaCode);
} catch (Exception e) {
e.printStackTrace();
}
if(!resultTpye.equals(false) || resultTpye != null){
//插入成功
result.setCode(CommonAPI.CODE_200000.getCode());
result.setMessage(CommonAPI.CODE_200000.getMessage());
result.setData(resultTpye);
}else {
result.setCode(CommonAPI.CODE_500012.getCode());
result.setMessage(CommonAPI.CODE_500012.getMessage());
result.setData(resultTpye);
}
return result;
}
3.编写Service业务实现类
代码如下(示例):这边我想导入的是学生信息,信息中包含多张表
/**
* //excel文件解析 学生信息 插入数据库
* @param fileName
* @param file
* @param schoolId
* @param areaCode
* @return
* @throws Exception
*/
@Override
public Object importUserInfo(String fileName, MultipartFile file, String schoolId, String areaCode) throws Exception {
boolean notNull = false;
if (!fileName