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

相关推荐
QMY5205208 小时前
爬虫的意义
java·spring·tomcat·maven
lang201509289 小时前
Spring Boot Actuator深度解析与实战
java·spring boot·后端
懒羊羊不懒@9 小时前
Java—枚举类
java·开发语言·1024程序员节
zerolala9 小时前
Java容器常用方法
java·1024程序员节
m0_748240259 小时前
C++智能指针使用指南(auto_ptr, unique_ptr, shared_ptr, weak_ptr)
java·开发语言·c++
lang201509289 小时前
Spring注解配置全解析
java·后端·spring
Qyt-Coding9 小时前
flowable学习
java
崎岖Qiu9 小时前
【SpringAI篇01】:5分钟教会你使用SpringAI (1.0.0稳定版)
java·spring boot·后端·spring·ai
不光头强10 小时前
IDEA的基本设置和使用
java·ide·intellij-idea
毕设源码-朱学姐10 小时前
【开题答辩全过程】以 产品报价系统为例,包含答辩的问题和答案
java·eclipse