pox.xml添加依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
定义一个类,在每个属性上面添加@Excel注解,并设置name值,注意name的值要与excel文件中的字段一一对应
@Data
public class WeiUser implements Serializable {
private static final long serialVersionUID = 337215436114100948L;
@Excel(name = "id")
private Integer id;
@Excel(name = "openid")
private String openid;
@Excel(name = "nickname")
private String nickname;
@Excel(name = "sex")
private Integer sex;
@Excel(name = "city")
private String city;
@Excel(name = "country")
private String country;
@Excel(name = "province")
private String province;
@Excel(name = "headimgurl")
private String headimgurl;
@Excel(name = "subscribe")
private String subscribe;
@Excel(name = "language")
private String language;
@Excel(name = "remark")
private String remark;
private Integer[] ids;
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="file"/>
<input type="submit" value="提交上传"/>
</form>
</body>
</html>
controller层代码
导入
//导入表格
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
ImportParams params = new ImportParams();
params.setHeadRows(1);
// 解析excel文件,得到的result是一个包含所有记录的集合
List<WeiUser> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
WeiUser.class, params);
//调用service层的add方法将集合中的每条数据插入到数据库
userService.addList(result);
return "success";
}
导出
//导出表格
@RequestMapping("/out")
public String exportCompanyImg(HttpServletRequest request) throws Exception {
//调用service层的方法获取数据库中数据,返回一个list集合
List<WeiUser> list = userService.getList();
File savefile = new File("F:/excel/");
//如果指定路径没有excel目录就创建一个
if (!savefile.exists()) {
savefile.mkdirs();
}
//将list集合转换成workbook文件
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), WeiUser.class, list);
//指定导出文件的存储路径
FileOutputStream fos = new FileOutputStream("F:/excel/ExcelExportHasImgTest.exportCompanyImg.xls");
//将文件写入指定位置
workbook.write(fos);
//关流
fos.close();
return this.getList(request,null,null);
}