Springboot使用POI实现导出Excel文件示例

论坛 期权论坛 脚本     
niminba   2021-5-23 05:25   888   0

前面讲述了使用POI导出Word文件和读取Excel文件,这两个例子都相对简单,接下来要讲述的使用POI导出Excel文件要复杂得多,内容也会比较长。

创建表头信息

表头信息用于自动生成表头结构及排序

public class ExcelHeader implements Comparable<ExcelHeader>{
 /**
  * excel的标题名称
  */
 private String title;
 /**
  * 每一个标题的顺序
  */
 private int order;
 /**
  * 说对应方法名称
  */
 private String methodName;


 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public int getOrder() {
  return order;
 }
 public void setOrder(int order) {
  this.order = order;
 }
 public String getMethodName() {
  return methodName;
 }
 public void setMethodName(String methodName) {
  this.methodName = methodName;
 }

 public int compareTo(ExcelHeader o) {
  return order>o.order?1:(order<o.order?-1:0);
 }
 public ExcelHeader(String title, int order, String methodName) {
  super();
  this.title = title;
  this.order = order;
  this.methodName = methodName;
 }
}

表头信息的Annotation

/**
 * 用来在对象的get方法上加入的annotation,通过该annotation说明某个属性所对应的标题
 * Created by 钟述林 on 2016/10/29 0:14.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
 /**
  * 属性的标题名称
  * @return
  */
 String title();
 /**
  * 在excel的顺序
  * @return
  */
 int order() default 9999;
}

创建数据实体

public class WebDto {

 //网站名称
 private String name;

 //网址
 private String url;

 //用户名
 private String username;

 //密码
 private String password;

 //日均访问量
 private Integer readCount;

 public WebDto(String name, String url, String username, String password, Integer readCount) {
  this.name = name;
  this.url = url;
  this.username = username;
  this.password = password;
  this.readCount = readCount;
 }

 public WebDto() {}

 @Override
 public String toString() {
  return "WebDto{" +
    "name='" + name + '\'' +
    ", url='" + url + '\'' +
    ", username='" + username + '\'' +
    ", password='" + password + '\'' +
    ", readCount=" + readCount +
    '}';
 }

 @ExcelResources(title="网站名称",order=1)
 public String getName() {
  return name;
 }

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

 @ExcelResources(title="网址",order=2)
 public String getUrl() {
  return url;
 }

 public void setUrl(String url) {
  this.url = url;
 }

 @ExcelResources(title="用户名",order=3)
 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 @ExcelResources(title="密码",order=4)
 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @ExcelResources(title="日均访问量",order=5)
 public Integer getReadCount() {
  return readCount;
 }

 public void setReadCount(Integer readCount) {
  this.readCount = readCount;
 }
}

注意:这里使用到了@ExcelResources来自动识别表头信息及序号

获取模板文件的工具类

public class TemplateFileUtil {

 public static FileInputStream getTemplates(String tempName) throws FileNotFoundException {
  return new FileInputStream(ResourceUtils.getFile("classpath:excel-templates/"+tempName));
 }
}

注意:从这里可以看出,所有的Excel模板文件都放在resources/excel-templates/目录下。

模板工具类

通过此类可以自动复制表样式等功能

/**
 * 该类实现了基于模板的导出
 * 如果要导出序号,需要在excel中定义一个标识为sernums
 * 如果要替换信息,需要传入一个Map,这个map中存储着要替换信息的值,在excel中通过#来开头
 * 要从哪一行那一列开始替换需要定义一个标识为datas
 * 如果要设定相应的样式,可以在该行使用styles完成设定,此时所有此行都使用该样式
 * 如果使用defaultStyls作为表示,表示默认样式,如果没有defaultStyles使用datas行作为默认样式
 * Created by 钟述林 393156105@qq.com on 2016/10/28 23:38.
 */
public class ExcelTemplate {

 /**
  * 数据行标识
  */
 public final static String DATA_LINE = "datas";
 /**
  * 默认样式标识
  */
 public final static String DEFAULT_STYLE = "defaultStyles";
 /**
  * 行样式标识
  */
 public final static String STYLE = "styles";
 /**
  * 插入序号样式标识
  */
 public final static String SER_NUM = "sernums";
 private static ExcelTemplate et = new ExcelTemplate();
 private Workbook wb;
 private Sheet sheet;
 /**
  * 数据的初始化列数
  */
 private int initColIndex;
 /**
  * 数据的初始化行数
  */
 private int initRowIndex;
 /**
  * 当前列数
  */
 private int curColIndex;
ing mn = m.getName();
   if(mn.startsWith("get")) {
    if(m.isAnnotationPresent(ExcelResources.class)) {
     ExcelResources er = m.getAnnotation(ExcelResources.class);
     headers.add(new ExcelHeader(er.title(),er.order(),mn));
    }
   }
  }
  return headers;
 }

 private Map<Integer,String> getHeaderMap(Row titleRow,Class clz) {
  List<ExcelHeader> headers = getHeaderList(clz);
  Map<Integer,String> maps = new HashMap<Integer, String>();
  for(Cell c:titleRow) {
   String title = c.getStringCellValue();
   for(ExcelHeader eh:headers) {
    if(eh.getTitle().equals(title.trim())) {
     maps.put(c.getColumnIndex(), eh.getMethodName().replace("get","set"));
     break;
    }
   }
  }
  return maps;
 }
}

Excel模板文件

创建一个模板文件,如下图:

POI导出Excel的模板文件

POI导出Excel的模板文件

测试类

@SpringBootTest
@RunWith(SpringRunner.class)
public class ExportExcelTest {

 @Test
 public void test() throws Exception {
  List<WebDto> list = new ArrayList<WebDto>();
  list.add(new WebDto("知识林", "http://www.zslin.com", "admin", "111111", 555));
  list.add(new WebDto("权限系统", "http://basic.zslin.com", "admin", "111111", 111));
  list.add(new WebDto("校园网", "http://school.zslin.com", "admin", "222222", 333));

  Map<String, String> map = new HashMap<String, String>();
  map.put("title", "网站信息表");
  map.put("total", list.size()+" 条");
  map.put("date", getDate());

  ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "web-info-template.xls", new FileOutputStream("D:/temp/out.xls"),
    list, WebDto.class, true);
 }

 private String getDate() {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
  return sdf.format(new Date());
 }
}

执行测试方法后,查看D:/temp/out.xls文件后可以看到如下图的内容:

POI导出Excel结果图

POI导出Excel结果图

下载地址:Springboot_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持社区。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP