easyexcel poi根据模板导出Excel

1.导入依赖

xml 复制代码
<!--    poi依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<!--    poi对于excel 2007的支持依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>
<!--    poi对于excel 2007的支持依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.0.1</version>
</dependency>

2.代码实现

java 复制代码
package com.example.exceldemo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class EasyExcelTest {

    public static void main(String[] args) throws Exception {
        InputStream fis = null;
        OutputStream outputStream= null;
        Workbook wb = null;
        try {
            String fileName = "测试单位"+ UUID.randomUUID() + ".xlsx";
            String filePath = "D:\\report\\"+fileName;
            //1.获取数据
            List<ExcelVo> list = new ArrayList<>();
            list.add(new ExcelVo(1,"1221","黄山"));
            list.add(new ExcelVo(2,"3333","河水"));
            list.add(new ExcelVo(3,"6666","青石"));

            //2.获取模板
            fis = new ClassPathResource("templates/report_template.xlsx").getInputStream();
            File file=new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);

            //3.根据模板创建工作簿
            wb = new XSSFWorkbook(fis);

            //4.读取工作表
            Sheet sheet = wb.getSheetAt(0);
            CellStyle styles[] = new CellStyle[row.getLastCellNum()];

            //5.抽取第2行的公共样式 , 因为第一行 为标题 第2行是数据 下标为1
            Row row = sheet.getRow(1);
            CellStyle styles[] = new CellStyle[row.getLastCellNum()];
            Cell cell = null;
            for (int i = 0; i < row.getLastCellNum(); i++) {
                cell = row.getCell(i);
                styles[i] = cell.getCellStyle();
            }

            //5.构造单元格
            int rowIndex=1;
            //方式一 手动
            for (ExcelVo vo2:list) {
                //创建每一行,同excel的第二行开始
                row= sheet.createRow(rowIndex++);
                //第一列
                int i=0;
                cell = row.createCell(i++);
                cell.setCellStyle(styles[0]);
                cell.setCellValue(vo2.getId());//写入数据 序号

                //第二列
                cell = row.createCell(i++);
                cell.setCellStyle(styles[0]);
                cell.setCellValue(vo2.getCode());

                //第三列(注:最后一列不用i++,前面的必须i++)
                cell = row.createCell(i);
                cell.setCellStyle(styles[0]);
                cell.setCellValue(vo2.getName());
            }

            //方式二 动态
            for (ExcelVo t:list) {
                //创建每一行,同excel的第二行开始
                row = sheet.createRow(rowIndex++);

                Field[] fields=t.getClass().getDeclaredFields();//获取filed
                for (int i = 0; i < fields.length; i++) {
                    Field field=fields[i];
                    field.setAccessible(true);//设置私有属性可以访问
                    Object val = field.get(t);//获取值
                    if (val==null)val="";
                    cell = row.createCell(i);
                    cell.setCellStyle(styles[0]);//设置单元格样式
                    cell.setCellValue(val.toString());//写入数据
                }
            }

            wb.write(outputStream);//写入数据
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            fis.close();
            wb.close();
            outputStream.close();
        }
    }
}

3.模板

参考:https://blog.csdn.net/weixin_45742032/article/details/119593288?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-119593288-blog-86538258.235%5Ev38%5Epc_relevant_anti_t3_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-119593288-blog-86538258.235%5Ev38%5Epc_relevant_anti_t3_base&utm_relevant_index=2

相关推荐
人道领域1 小时前
Day | 11 【苍穹外卖统计业务的实现:含详细思路分析】
java·数据库·后端·苍穹外卖
xiaoye37086 小时前
Java 自动装箱 / 拆箱 原理详解
java·开发语言
蒸蒸yyyyzwd7 小时前
day3学习笔记
笔记·学习
YDS8298 小时前
黑马点评 —— 分布式锁详解加源码剖析
java·spring boot·redis·分布式
迷藏4948 小时前
**发散创新:基于 Rust的开源权限管理系统设计与实战**在现代软件架构中,**权限控制**早已不
java·开发语言·rust·开源
升鲜宝供应链及收银系统源代码服务8 小时前
《IntelliJ + Claude Code + Gemini + ChatGPT 实战配置手册升鲜宝》
java·前端·数据库·chatgpt·供应链系统·生鲜配送
daidaidaiyu8 小时前
Nacos实例一则及其源码环境搭建
java·spring
小江的记录本9 小时前
【Redis】Redis全方位知识体系(附《Redis常用命令速查表(完整版)》)
java·数据库·redis·后端·python·spring·缓存
摇滚侠9 小时前
Java 项目《谷粒商城-1》架构师级Java 项目实战,对标阿里 P6-P7,全网最强,实操版本
java·开发语言
zihao_tom9 小时前
Spring Boot(快速上手)
java·spring boot·后端