c語(yǔ)言 做網(wǎng)站seo優(yōu)化標(biāo)題
Spring boot集成easy excel
一 查看官網(wǎng)
easyexcel官方網(wǎng)站地址為easyexcel官網(wǎng),官網(wǎng)的信息比較齊全,可以查看官網(wǎng)使用easyexcel的功能。
二 引入依賴
使用easyexcel,首先要引入easyexcel的maven依賴,具體的版本根據(jù)你的需求去設(shè)置。
<!--easyexcel--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.10</version></dependency>
三 實(shí)現(xiàn)簡(jiǎn)單導(dǎo)入
首先定義實(shí)體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Device {@ExcelIgnoreprivate Integer id;@ExcelProperty("設(shè)備名稱")private String name;@ExcelProperty("設(shè)備編號(hào)")private String no;@ExcelProperty("設(shè)備描述")private String description;@ExcelProperty("設(shè)備類型")private Integer type;@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@ExcelIgnoreprivate LocalDateTime createTime;@ExcelIgnoreprivate Integer status;
}
在定義實(shí)體類的時(shí)候,使用到了lombok,需要提前引入lombok的依賴
<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
準(zhǔn)備工作完成之后,就可以寫一個(gè)簡(jiǎn)單的導(dǎo)入了。如下,我在controller中寫了導(dǎo)入方法,通過(guò)EasyExcel的read方法把excel中的數(shù)據(jù)解析成對(duì)應(yīng)的列表,然后就可以直接調(diào)用service導(dǎo)入了。
@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";}
四 實(shí)現(xiàn)簡(jiǎn)單導(dǎo)出
在controller寫了簡(jiǎn)單的導(dǎo)出方法,拿到service得到的數(shù)據(jù),就可以直接調(diào)用EasyExcel的write方法導(dǎo)出了。
@GetMapping("export")public void export(Dto dto,HttpServletResponse response) throws IOException {// 這里注意 有同學(xué)反應(yīng)使用swagger 會(huì)導(dǎo)致各種問(wèn)題,請(qǐng)直接用瀏覽器或者用postmanresponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 這里URLEncoder.encode可以防止中文亂碼 String fileName = URLEncoder.encode("設(shè)備數(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);}
五 批量導(dǎo)出功能
請(qǐng)參考easyexcel實(shí)現(xiàn)批量導(dǎo)出功能
總結(jié)
使用easyexcel實(shí)現(xiàn)導(dǎo)入和導(dǎo)出確實(shí)是非常方便的,同時(shí),easyexcel還支持批量導(dǎo)入和批量導(dǎo)出,確實(shí)非常nice。