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

相关推荐
事圆则缓24 分钟前
Java 转 Kotlin 的 Android 迁移路线
java
计算机毕设定制辅导-无忧学长30 分钟前
《基于Vue的流浪动物救助中心管理系统的设计与实现》
java·vue.js·spring boot·流浪动物救助中心管理系统
Mikko733 分钟前
jackson-databind 升到 2.21.6 就安全了吗?jackson-core 是另一个坐标,它那条 high 全局库至今没收
java·后端·安全·json
Java_AI工程师34 分钟前
90%的人写Function Calling,只写了"把参数传给工具执行"这一步,剩下的参数校验、错误重试、超时控制、结果格式化,全是空白。
java·人工智能·程序员
斯维赤37 分钟前
LangChain4j 入门教学(Java 后端狂喜版
java·后端
Java_2017_csdn40 分钟前
Java 8 Stream API 中的 map 和 flatMap 详解
java
AI深栈1 小时前
第 15 章 · 第一个 AI 工作流:Hello Graph 从 START 跑到 END
java·人工智能
搜狐技术产品小编20231 小时前
解锁Kotlin Serialization高阶玩法:详解4种自定义序列化器与动态上下文策略
java·人工智能
花间相见1 小时前
【计算基础|网络04】—— HTTP接口实战(下):接口测试、鉴权与跨域排错
java·linux·人工智能·后端·python·计算机网络·postman