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();
        }
    }
}
相关推荐
yiangL_1 分钟前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
用户9338104348456 分钟前
MyBatis-Plus LambdaQueryWrapper 隐式转换踩坑:不知不觉索引失效
java
用户37215742613512 分钟前
Java 在 PDF 中查找关键词:获取页码和坐标,并高亮匹配结果
java
Forget the Dream38 分钟前
Spring AI 2.0 系列(三):ChatClient 与 ChatModel:Spring AI 2.0 的两层职责
java·人工智能·spring·springai
Rain的Java大神之路2 小时前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
山楂树の2 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
利威尔xu2 小时前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
跳跳的小古风3 小时前
前端转全栈:一条接口从前端请求到 SQL 完整流程
java·前端
eggwyw4 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
布莱克6054 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举