<dependency>
<groupId>net.oschina.likaixuan</groupId>
<artifactId>excelutil</artifactId>
<version>3.0.1</version>
</dependency>
+、web前端上传注意事项
<form action="/e2/t4" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="submit">
</form>
+、后端代码注意事项
读取excel表格 并返回表格内容数据 (采用pojo类接收)
Excel2.java 如下:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Excel2 {
@Excel(title = "姓名")
private String name;
@Excel(title = "性别")
private String sex;
@Excel(title = "年龄")
private String age;
@Excel(title = "地址")
private String address;
@Excel(title = "电话")
private String phone;
}
接收文件 读取excel文件内容 自动组装到实体类中:
public Object t1(MultipartFile file) throws Exception {
List<Excel2> excel2List = ExcelUtil.readXls(file.getBytes(), Excel2.class);
excel2List.forEach(excel2 -> {
excel2.setAddress("南京");
});
return excel2List;
}
保存文件 将数据封装到实体类集合 然后导出到前端浏览器
public void t2(HttpServletResponse response) throws Exception {
List<Excel2> excel2List = Arrays.asList(
new Excel2("张三", "男", "22", "北京市", "17758586428"),
new Excel2("张三", "男", "22", "北京市", "17775853428"),
new Excel2("张三", "男", "22", "北京市", "17777585428"),
new Excel2("张三", "男", "22", "北京市", "17777585428"),
new Excel2("张三", "男", "22", "北京市", "17772477588"),
new Excel2("张三", "男", "22", "北京市", "17777585428"),
new Excel2("张三", "男", "22", "北京市", "17777758428")
);
log.info("下载了一份excel表格");
ExcelUtil.exportExcelOutputStream(response, excel2List, Excel2.class);
}
ExcelUtil 省去了繁琐的读取excel步骤,仅仅只用打开文件,读取内容,自动赋值到我们所定义的实体类中,自动匹配我们定义的数据类型,在我们使用读取和写入excel实现了便利。