POI-tl 知识整理:整理1 -> 利用模板向word中写入数据

1 文本传值

java 复制代码
    @Test
    public void testText() throws Exception {
        XWPFTemplate template = XWPFTemplate.compile("D:\\Idea-projects\\POI_word\\templates.docx");
        Map<String, Object> map = new HashMap<>();
        map.put("title", "Hi, girl");
        template.render(map);

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\Idea-projects\\POI_word\\output.docx");
        template.writeAndClose(fileOutputStream);

        template.close();
    }

2 对象传值

java 复制代码
public class Student {
    private  String name;
    private  int age;
    private  String sex;

    // getter and setter

}

java 复制代码
    @Test
    public void testObject() throws Exception{
        // 数据可以是对象
        Student student = new Student();
        student.setName("小蟹");
        student.setAge(20);
        student.setSex("男");

        XWPFTemplate template = XWPFTemplate.compile("D:\\Idea-projects\\POI_word\\templates1.docx");
        Map<String, Object> map = new HashMap<>();
        map.put("name", student.getName());
        map.put("age", student.getAge());
        map.put("sex", student.getSex());
        template.render(map);

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\Idea-projects\\POI_word\\output_object.docx");
        template.writeAndClose(fileOutputStream);

        template.close();
    }

3 Map 传值

java 复制代码
    // Map 传值
    @Test
    public void testMapping() throws Exception{
        // 数据可以是Map集合
        Map<String, Object> data = new HashMap<>();
        data.put("name", "小草");
        data.put("age", 22);
        data.put("sex", "女");

        XWPFTemplate template = XWPFTemplate.compile("D:\\Idea-projects\\POI_word\\templates1.docx");

        Map<String, Object> map = new HashMap<>();
        map.put("map", data);
        XWPFTemplate render = template.render(map);

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\Idea-projects\\POI_word\\output_map.docx");
        template.writeAndClose(fileOutputStream);

        template.close();  // 一定要记得关闭
    }

相关推荐
香香甜甜的辣椒炒肉7 分钟前
Spring(1)基本概念+开发的基本步骤
java·后端·spring
成都渲染101云渲染66661 小时前
跳出“硬件堆砌”陷阱|渲染101如何用技术重构云渲染的专业价值?
java·前端·javascript
golang学习记1 小时前
IDEA 2026.1全新调试新特性:Spring Boot调试不再靠猜!
java·spring boot·intellij-idea
橘子编程1 小时前
OpenClaw(小龙虾)完整知识汇总
java·前端·spring boot·spring·spring cloud·html5
大阿明1 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
Binary-Jeff1 小时前
Spring 创建 Bean 的关键流程
java·开发语言·前端·spring boot·后端·spring·学习方法
rOuN STAT2 小时前
MySQL:基础操作(增删查改)
java
→长歌2 小时前
2026Java面试30题精解
java·python·面试
SHoM SSER2 小时前
Spring Boot性能提升的核武器,速度提升500%!
java·spring boot·后端
weixin_425023002 小时前
Spring Boot 2.7 + JDK8 集成 Knife4j 4.1.0 教程(仅展示带注解接口)
java·spring boot·后端