关于easyExcel的个人理解

对于easyExcel的理解
easyExcel是阿里的一个针对Java poi 做的一个开源框架。能够简化Java poi 所需要的内存损耗。大大减轻程序员的工作,提高效率。提供了两种方法填入数据。

以下是我的个人理解(基于springboot项目):
所需要的jar包是(spring boot的导包在pom.xml中加入,这里给的jar包只是使用这个开源框架所需要的jar包名称而已):
在这里插入图片描述

第一种方式:不使用自定义模板,自动生成表格
整体:
在这里插入图片描述

1.实体类:
实体类要继承BaseRowMode,封装和构造,以及tostring(),
封装和构造可以用lombok的@Data和@Builder代替,但是对于初学者不太友好,容易报错和看不懂代码。建议不使用lombok。封装以及构造是常用的。

实体类代码:

package cn.poiText.pojo;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;

public class User extends BaseRowModel{

	@ExcelProperty(value = "编号",index = 0)
	private Integer id;
	
	@ExcelProperty(value = "姓名",index = 1)
	private String name;
	
	@ExcelProperty(value = "时间",index = 2)
	private Date createTime;
	
	@ExcelProperty(value = "操作事务",index = 3)
	private String operation;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", createTime=" + createTime + ", operation=" + operation + "]";
	}

	public User(Integer id, String name, Date createTime, String operation) {
		super();
		this.id = id;
		this.name = name;
		this.createTime = createTime;
		this.operation = operation;
	}

	public User() {
		super();
	}
}

注意:@ExcelProperty(value = “编号”,index = 0) 是设置表头和位置。不使用自定义模板的时候需要加上。

控制器代码:

package cn.poiText.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;

import cn.poiText.pojo.User;
import cn.poiText.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/getAllUser.do")
    @ResponseBody
	public List<User> getAllUser(){
		
		//统计数据库一共有多少数据,进行判断进行循环遍历数组
		int total = userService.findCnt();
		
		//新建一个集合存储数据
        List<User> userList = new ArrayList<>();
        
        //判断数据库是否有数据,如果没有则不进行遍历数据
        if (total>0) {
        	 for (int i=0;i<total;i++){
        		
        		//查询数据
             	User listUser =userService.findInfo(i+1);
             	
             	//填入数据
                User user =new User(listUser.getId(), listUser.getName(), listUser.getCreateTime(), listUser.getOperation());
                
                //加入集合
                userList.add(user);
             }
		}
        
         
        System.out.println(userList);
		
        return userList;
	}
	
	@ResponseBody
	@RequestMapping("downString.do")
	public boolean downString() {
		
		// 文件输出位置
        OutputStream out = null;
        try {
        	
            out = new FileOutputStream("f:\\wind\\日志.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(out);
 
            // 写仅有一个 Sheet 的 Excel 文件, 此场景较为通用
            Sheet sheet1 = new Sheet(1, 0, User.class);
 
            // 第一个 sheet 名称
            sheet1.setSheetName("第一个sheet");
 
            // 写数据到 Writer 上下文中
            // 入参1: 数据库查询的数据list集合
            // 入参2: 要写入的目标 sheet
            writer.write(getAllUser(), sheet1);
 
            // 将上下文中的最终 outputStream 写入到指定文件中
            writer.finish();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true; 
	}
}

注:文件输出的位置可以任意调换,日志.xlsx这个名字也可以随意更改,但是不可漏后缀名。
然后就可以在页面中进行测试了。
在这里插入图片描述
返回true,成功导出数据了。
在这里插入图片描述
在这里插入图片描述

第二种方法(需要自己定义模板,然后将数据填入自定义的模板中。参考:语雀:https://www.yuque.com/easyexcel/doc/easyexcel):
一:需要自定义一个模板
在这里插入图片描述
其中的{.id},{.name},{.createTime},{.operation}相当于一个集合,等待程序从数据库查询出来插数据进去,名字与数据库表名需一致。

二:实体类与第一种方法一致,需要进行封装,构造,继承以及tostring。

三:控制器
首先定义模板所在的地址以及导出的地址。

     //模板地址  其实就是f:\\wind\\操作日志.xlsx
	 private static final String template_path="f:"+ File.separator+"wind"+File.separator+"操作日志.xlsx";
	 
	 //导出数据的表格的地址f:\\wind\\winds\\fill3.xlsx
	 private static final String fill_path="f:"+ File.separator+"wind"+File.separator+"winds"+File.separator+"fill3.xlsx";

其次数据库中查询数据

     @RequestMapping("getAllUser")
	 @ResponseBody
	 private List<User> getAllUser() throws ParseException{
		 
		 	int total = userService.findCnt();//统计数据库有多少数据,用于判断计算返回多少数据
		 	
	        List<User> list=new ArrayList<>();
	        for (int i=0;i<total;i++){
	        	User userLists =userService.findInfo(i+1);//遍历数组,填充进表格
	        	
	        	User user = new User(userLists.getId(), userLists.getName(),userLists.getCreataTime(),userLists.getOperation());
	        	
	            list.add(user);
	        }
	 
	        return list;
	    }

填充数据

     @ResponseBody
	 @RequestMapping("fill.do")
	 public int fill(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		 	
	        EasyExcel.write(fill_path).withTemplate(template_path).sheet().doFill(getAllUser());
	        
	        return 1;
	    }

整合代码:

//模板地址 其实就是f:\\wind\\操作日志.xlsx
	 private static final String template_path="f:"+ File.separator+"wind"+File.separator+"操作日志.xlsx";
	 
	 //导出数据的表格的地址f:\\wind\\winds\\fill3.xlsx
	 private static final String 
	 fill_path="f:"+ File.separator+"wind"+File.separator+"winds"+File.separator+"fill3.xlsx";//导出的数据表格的位置,注意:不能自动建文件夹。
	 
	 @RequestMapping("getAllUser")
	 @ResponseBody
	 private List<User> getAllUser() throws ParseException{
		 
		 	int total = userService.findCnt();//统计数据库有多少数据,用于判断计算返回多少数据
		 	
	        List<User> list=new ArrayList<>();
	        for (int i=0;i<total;i++){
	        	User userLists =userService.findInfo(i+1);//遍历数组,填充进表格
	        	
	        	User user = new User(userLists.getId(), userLists.getName(),userLists.getCreataTime(),userLists.getOperation());
	        	
	            list.add(user);
	        }
	 
	        return list;
	    }

	 	
	 @ResponseBody
	 @RequestMapping("fill.do")
	 public int fill(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		 	
	        EasyExcel.write(fill_path).withTemplate(template_path).sheet().doFill(getAllUser());
	        
	        return 1;
	    }

运行得到结果:
在这里插入图片描述
搞定收工吃饭。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值