相信在web开发中,很多人都会遇到批量导入/导出的需求,下面就为大家介绍web开发中Excel中的导入导出
一、导入依赖
提示:以下是本篇文章正文内容,下面案例可供参考
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.4</version>
</dependency>
二、导入导出的模型数据
@Data
@ContentRowHeight(10)
@HeadRowHeight(15)
@ColumnWidth(20)
public class OrderVO {
@ExcelProperty({"订单表信息","id"})
private int id;
@ExcelProperty({"订单表信息","订单号"})
private String orderNo;
@ExcelProperty({"订单表信息","货主id"})
private int huoZuId;
@ExcelProperty({"订单表信息","承运商id"})
private int carryId;
@ExcelProperty({"订单表信息","交易价格"})
private BigDecimal money;
@ExcelProperty({"订单表信息","起源地"})
private String from;
@ExcelProperty({"订单表信息","目的地"})
private String to;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty({"订单表信息","创建日期"})
private Date gmtCreate;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty({"订单表信息","修改日期"})
private Date gmtUpdate;
}
三、Excel数据的导出
常用于批量导出,示例代码:
@ApiOperation("下载订单")
@GetMapping("/{num}/{size}")
public void orderPage(@PathVariable("num") int pageNum, @PathVariable("size") int pageSize) throws IOException {
PageHelper.startPage(pageNum,pageSize);
PageInfo<OrderVO> orderPages = new PageInfo(orderService.orderPage());
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
EasyExcel.write(response.getOutputStream(), OrderVO.class).sheet("表1").doWrite(orderPages.getList());
return ;
}
四、Excel数据的导入
常用在批量导入数据,示例代码:
@ApiOperation("导入excel的数据到后端")
@PostMapping("/export")
public InfoResultVO export(MultipartFile file) throws IOException {
final List<OrderVO> list = new ArrayList();
EasyExcel.read(file.getInputStream(), OrderVO.class, new AnalysisEventListener<OrderVO>() {
@Override
public void invoke(OrderVO data, AnalysisContext context) {
log.info("解析每一条数据{}",data);
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("解析完成{}",list);
}
}).sheet("表1").doRead();
return new InfoResultVO(200,null,"导入数据成功");
}
总结
想要更进一步了解学习,参考阿里云链接:https://developer.aliyun.com/article/787306#slide-3 文章其实还存在个小问题,就是日期信息的导入导出不准确,还待优化
|