Java使用easyexcel导出到excel并下载

Java使用easyexcel导出到excel并下载

使用工具easyexcel
工具介绍:easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到KB级别,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便

比Hutool导出excel还要简单

1,pom文件

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>{latestVersion}</version>
</dependency>

2,Java映射模型

旧方法

在这里插入图片描述
需要注意的就是红框两点

更新

根据最新更新的git上来看,不需要继承BaseRowModel了,这也符合使用习惯
只需要注解 @ExcelProperty(value = “标识” ,index = 0),不需要加入到excel列中只需要加注解 @ExcelIgnore

3,controller层

旧方法

~~@GetMapping("/download")
	public void download(HttpServletResponse response,PageQuery page ,Date time ,String keyword,String[] levelArr, String[] typeArr, String[] substationArr, String[] equipmentArr) {
		OutputStream out = null;
		ExcelWriter writer = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    		String date = sdf.format(new Date());
    		//通过查询组装数据
    		List<Alarm> alarmlist = alarmService.downloadResults(pageDate, time, "测试", levelArr, typeArr, substationArr, equipmentArr);
    		//拼接导出的文件名
    		//String fileName = new String(("告警信息"+date).getBytes("UTF-8"),"ISO-8859-1")+".xlsx";
    		String fileName = date + new String(("告警数据").getBytes("UTF-8"),"ISO-8859-1") + ".xlsx";
    		//response.setCharacterEncoding("utf-8");
            //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);
    		//下载到浏览器默认地址
    		out = response.getOutputStream();
    		writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
    		Sheet sheet1 = new Sheet(1, 0, Alarm.class);
            sheet1.setSheetName("sheet1");
    		writer.write(alarmlist, sheet1);
    		alarmlist.clear();
		} catch (Exception e) {
			log.error("告警信息下载失败"+e.getMessage(),e);
		} finally {
			try {
				out.flush();
				writer.finish();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}~~ 

使用方式也有更新

@GetMapping("/download")
    public void download(HttpServletResponse response,Integer page, Integer size, String types, Date startTime, Date deadline, String likeWord){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            List<Event> alarmlist = service.download(page, size, types, startTime, deadline, likeWord);
            String fileName = "Alarm"+date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            EasyExcel.write(response.getOutputStream(), Event.class).sheet("模板").doWrite(alarmlist);
        } catch (Exception e) {
            log.error("告警信息下载失败"+e.getMessage(),e);
        }
    }

需要注意的是,导出的文件名,不可以有空格,也就是new SimpleDateFormat(“yyyyMMddHHmm”);不可以写成new SimpleDateFormat(“yyyyMMdd HHmm”);

4,导出文件格式
在这里插入图片描述

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
文件时,如何设置单元格样式? A:使用easyexcel模板导出Excel文件时,可以通过设置注解@ExcelProperty的style属性来指定对应单元格的样式。具体操作如下: 1. 定义样式类,继承自com.alibaba.excel.write.style.AbstractCellStyleStrategy,重写setCellStyle方法,对单元格样式进行设置。示例代码如下: ``` public class CustomCellStyleStrategy extends AbstractCellStyleStrategy { private CellStyle cellStyle; public CustomCellStyleStrategy(Workbook workbook) { this.cellStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontName("微软雅黑"); font.setFontHeightInPoints((short) 12); cellStyle.setFont(font); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setBorderTop(BorderStyle.THIN); cellStyle.setBorderRight(BorderStyle.THIN); cellStyle.setBorderBottom(BorderStyle.THIN); cellStyle.setBorderLeft(BorderStyle.THIN); } @Override protected CellStyle setCellStyle(Cell cell, Head head, Integer integer, Integer integer1) { return cellStyle; } } ``` 2. 在需要导出的实体类中,为需要定制样式的属性添加@ExcelProperty注解,设置style属性为对应的样式类。示例代码如下: ``` public class User { @ExcelProperty(value = "姓名", index = 0, style = CustomCellStyleStrategy.class) private String name; @ExcelProperty(value = "年龄", index = 1) private Integer age; // ... } ``` 在注解中,value属性指定了单元格的标题,index属性指定了导出的顺序,style属性指定了样式类。 通过以上步骤,即可设置单元格样式。需要注意的是,样式类需要在导出Excel时传入,如下示例代码: ``` List<User> userList = new ArrayList<>(); // ... 添加用户数据 // 构造导出参数对象 WriteWorkbook writeWorkbook = EasyExcel.write(fileName).build(); WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").head(User.class).registerWriteHandler(new CustomCellStyleStrategy(writeWorkbook.getWorkbook())).build(); // 执行导出 EasyExcel.write(fileName, User.class).sheet("Sheet1").build().write(userList); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值