java:poi导出word文档

导入依赖

<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>

复制代码
import org.apache.poi.xwpf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;

public class WordDocumentExporter {
    public void exportToWord(HttpServletResponse response, Object data) {
        XWPFDocument document = new XWPFDocument();

        // 创建表格
        XWPFTable table = document.createTable();
        XWPFTableRow headerRow = table.getRow(0);
        headerRow.getCell(0).setText("属性名");
        headerRow.addNewTableCell().setText("属性值");

        // 获取类的所有属性
        Field[] fields = data.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String fieldValue = "";
            try {
                Object value = field.get(data);
                fieldValue = value != null ? value.toString() : "";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            XWPFTableRow row = table.createRow();
            row.getCell(0).setText(fieldName);
            row.getCell(1).setText(fieldValue);
        }

        try {
            // 设置响应头
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment; filename=output.docx");

            // 输出到浏览器
            document.write(response.getOutputStream());
            response.getOutputStream().close();
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
CS创新实验室4 分钟前
《计算机网络》深入学:轮询和令牌传递协议
开发语言·计算机网络·考研·php·408
MonkeyKing_sunyuhua7 分钟前
ES文档序号写错的问题的修复
java·数据库·elasticsearch
小豪GO!9 分钟前
Spring-八股
java·spring boot·spring
王干脆17 分钟前
ConcurrentHashMap禁止null键值的原因
java·开发语言
牧小七21 分钟前
Java注解(Annotation)全面学习指南
java
开开心心就好23 分钟前
PDF密码移除工具,免费解除打印编辑复制权限
java·网络·windows·websocket·pdf·电脑·excel
代码游侠28 分钟前
ARM嵌入式开发代码实践——LED灯闪烁(C语言版)
c语言·开发语言·arm开发·笔记·嵌入式硬件·学习
—Qeyser30 分钟前
Flutter Text 文本组件完全指南
开发语言·javascript·flutter
咕噜企业分发小米34 分钟前
豆包大模型在药物研发中的知识检索效率如何?
java·开发语言·数据库
Remember_99334 分钟前
【LeetCode精选算法】二分查找专题一
java·数据结构·算法·spring·leetcode·哈希算法