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();
        }
    }
}
相关推荐
xu_ws5 分钟前
Spring-ai项目-deepseek-6-哄哄模拟器
java·人工智能·spring
刘 大 望7 分钟前
SpringAI Tool Calling(工具调用)
java·spring boot·spring·ai·maven·intellij-idea·文心一言
222you7 分钟前
Java 并发编程(1)
java·开发语言
C++ 老炮儿的技术栈16 分钟前
Linux 文件系统目录架构全解析
linux·服务器·c语言·开发语言·c++
2601_9534656129 分钟前
HLS.js 原生开发!m3u8live.cn打造最贴合项目的 M3U8 在线播放器
开发语言·前端·javascript·python·json·ecmascript·前端开发工具
岁岁种桃花儿32 分钟前
kubenetes从入门到上天系列第十九篇:Kubernetes安装Nginx ingress controller
java·nginx·kubernetes
做一个AK梦40 分钟前
RedisForValueService.setIfAbsent()
java·分布式
szcsun540 分钟前
python中包、模块的层级关系,以及import、from...import...的相关用法
开发语言·python
Yvonne爱编码1 小时前
JAVA数据结构 DAY8-堆
java·数据结构·python
阿猿收手吧!1 小时前
【C++】高并发内存池架构与设计解析
开发语言·c++·架构