本次工作总结
- 完成Excel导入通用实现类
包括:ExcelUtil实现、通过文件数据导入新闻接口。
相关代码实现
ExcelUtil通用类
在pom.xml中导入所需依赖
org.apache.poi
poi
4.0.1
org.apache.poi
poi-ooxml
4.0.1
ExcelUtil类
public class ExcelUtils {
//泛型,通用任何实体类
private T t;
public ExcelUtils(T t){
this.t = t;
}
public List
ExcelUtil使用实例如下
新闻批量导入
这边通过Excel批量导入到数据库中,需要保证excel中列属性和实体类对应。
Controller层
@PostMapping("/uplodaNews")
public Result uploadNews(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename(); // 获取文件名
InputStream is = null;
try{
is = file.getInputStream();
List paperList = newsService.getListByExcel(is,fileName);// 获取解析后的List集合
System.out.println(paperList.toString());
Boolean result = newsService.batchImportStuInfo(paperList); // 把数据插入数据库
if (result){
return Result.success("上传成功");
}else {
return Result.fail(403,"上传失败");
}
}catch (Exception e){
e.printStackTrace();
} finally {
is.close();
}
return Result.fail(403,"文件出错");
}
Service层
从Excel中获取数据并封装成List列表形式
@Override
public List getListByExcel(InputStream is, String fileName) {
try{
List newsList = new ExcelUtils(new News()).analysisExcel(is, fileName);
return newsList;
}catch (Exception e){
e.printStackTrace();
}
return new ArrayList<>();
}
将List数据批量加入到数据库中
@Override
public Boolean batchImportStuInfo(List newslist) {
Integer flag = newsMapper.batchImportInfo(newslist);
if (flag > 0){
return true;
} else return false;
}
Mapper层
insert into t_news values
(#{item.id},#{item.title},#{item.content},#{item.time},#{item.link})
测试实例
这里自己写了个小的demo来测试这个接口。
测试demo结构如下:
导入效果:
总结
- ExcelUtil的编写既可以方便的导入Excel数据,又可以支撑后续的后台管理系统的更新数据的相应功能实现。
- 再次更行新闻的话不需要直接操作数据库了。