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

相关推荐
2401_8370885013 分钟前
stringRedisTemplate.opsForHash().entries
java·redis
lkbhua莱克瓦242 小时前
Java基础——集合进阶3
java·开发语言·笔记
蓝-萧2 小时前
使用Docker构建Node.js应用的详细指南
java·后端
多喝开水少熬夜2 小时前
Trie树相关算法题java实现
java·开发语言·算法
lkbhua莱克瓦243 小时前
Java基础——集合进阶用到的数据结构知识点1
java·数据结构·笔记·github
音符犹如代码4 小时前
Java并发List实战:CopyOnWriteArrayList原理与ArrayList常见面试题
java·开发语言·面试·list
代码or搬砖4 小时前
Docker 部署 Java 项目实践
java·docker·容器
又是忙碌的一天4 小时前
抽象类和接口
java·开发语言
August_._4 小时前
【MySQL】SQL语法详细总结
java·数据库·后端·sql·mysql·oracle
Dxxyyyy4 小时前
零基础学JAVA--Day26(枚举类)
java·开发语言