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

相关推荐
全栈凯哥32 分钟前
16.Spring Boot 国际化完全指南
java·spring boot·后端
M1A139 分钟前
Java集合框架深度解析:LinkedList vs ArrayList 的对决
java·后端
Top`43 分钟前
Java 泛型 (Generics)
java·开发语言·windows
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 小时前
如何使用Java WebSocket API实现客户端和服务器端的通信?
java·开发语言·websocket
是小崔啊1 小时前
tomcat源码02 - 理解Tomcat架构设计
java·tomcat
没有bug.的程序员2 小时前
JAVA面试宝典 -《安全攻防:从 SQL 注入到 JWT 鉴权》
java·安全·面试
栈溢出了2 小时前
MyBatis实现分页查询-苍穹外卖笔记
java·笔记·mybatis
morningcat20182 小时前
java17 gc笔记
java·jvm·笔记
2 小时前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
Your易元3 小时前
设计模式-模板方法模式
java·设计模式·模板方法模式