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();  // 一定要记得关闭
    }

相关推荐
梁同学与Android6 分钟前
Android ---【经验篇】ArrayList vs CopyOnWriteArrayList 核心区别,怎么选择?
android·java·开发语言
ss27319 分钟前
从零实现线程池:自定义线程池的工作线程设计与实现
java·开发语言·jvm
苗壮.21 分钟前
CommandLineRunner 是什么?
java
石工记26 分钟前
windows 10直接安装多个JDK
java·开发语言
菜鸟233号27 分钟前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
健康平安的活着1 小时前
springboot+sse的实现案例
java·spring boot·后端
05大叔1 小时前
多线程的学习
java·开发语言·学习
小萌新上大分1 小时前
synchronized的8锁问题(区分默认用的是那把锁) 笔记云备份
java·java多线程·synchronized·synchronized关键字·synchronized用法·多线程买票问题·java锁机制
sino爱学习2 小时前
别再踩 Stream 的坑了!Java 函数式编程安全指南
java·后端
Sunsets_Red2 小时前
2025 FZYZ夏令营游记
java·c语言·c++·python·算法·c#