c語言 做網(wǎng)站深圳龍崗區(qū)布吉街道
Spring boot集成easy excel
一 查看官網(wǎng)
easyexcel官方網(wǎng)站地址為easyexcel官網(wǎng),官網(wǎng)的信息比較齊全,可以查看官網(wǎng)使用easyexcel的功能。
二 引入依賴
使用easyexcel,首先要引入easyexcel的maven依賴,具體的版本根據(jù)你的需求去設置。
<!--easyexcel--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.10</version></dependency>
三 實現(xiàn)簡單導入
首先定義實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Device {@ExcelIgnoreprivate Integer id;@ExcelProperty("設備名稱")private String name;@ExcelProperty("設備編號")private String no;@ExcelProperty("設備描述")private String description;@ExcelProperty("設備類型")private Integer type;@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@ExcelIgnoreprivate LocalDateTime createTime;@ExcelIgnoreprivate Integer status;
}
在定義實體類的時候,使用到了lombok,需要提前引入lombok的依賴
<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
準備工作完成之后,就可以寫一個簡單的導入了。如下,我在controller中寫了導入方法,通過EasyExcel的read方法把excel中的數(shù)據(jù)解析成對應的列表,然后就可以直接調(diào)用service導入了。
@RequestMapping("save")public String save(MultipartFile file) throws IOException {String originalFilename = file.getOriginalFilename();List<Device> list = EasyExcel.read(file.getInputStream()).head(Device.class).sheet().doReadSync();deviceService.batchSave(list);return "redirect:/device/lists";}
四 實現(xiàn)簡單導出
在controller寫了簡單的導出方法,拿到service得到的數(shù)據(jù),就可以直接調(diào)用EasyExcel的write方法導出了。
@GetMapping("export")public void export(Dto dto,HttpServletResponse response) throws IOException {// 這里注意 有同學反應使用swagger 會導致各種問題,請直接用瀏覽器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 這里URLEncoder.encode可以防止中文亂碼 String fileName = URLEncoder.encode("設備數(shù)據(jù)", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");List<Device> deviceList = deviceService.getDeviceList(dto);EasyExcel.write(response.getOutputStream(), Device.class).sheet("數(shù)據(jù)").doWrite(deviceList);}
五 批量導出功能
請參考easyexcel實現(xiàn)批量導出功能
總結(jié)
使用easyexcel實現(xiàn)導入和導出確實是非常方便的,同時,easyexcel還支持批量導入和批量導出,確實非常nice。