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();
        }
    }
}
相关推荐
独自归家的兔3 分钟前
Java性能优化实战:从基础调优到系统效率倍增 - 1
java·开发语言·性能优化
小π军5 分钟前
C++ STL:array容器常见用法
开发语言·c++
Coder_Boy_5 分钟前
基于SpringAI的在线考试系统-DDD(领域驱动设计)核心概念及落地架构全总结 (2)
java·人工智能·spring boot·架构·serverless·ddd·服务网格
Coder_Boy_6 分钟前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解(2)
java·前端·数据库·人工智能·spring boot
156082072198 分钟前
在QT下添加QWT6.1.4功能
开发语言·qt
long31610 分钟前
弗洛伊德·沃肖算法 Floyd Warshall Algorithm
java·后端·算法·spring·springboot·图论
有一个好名字11 分钟前
力扣-咒语和药水的成功对数
java·算法·leetcode
minglie114 分钟前
micropython_spiFlash_w25qxx
开发语言·python
源代码•宸16 分钟前
Golang原理剖析(channel面试与分析)
开发语言·经验分享·后端·面试·golang·select·channel
H Corey25 分钟前
Java--面向对象之继承与多态
java·开发语言·windows·学习·算法·intellij-idea