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();
        }
    }
}
相关推荐
十五年专注C++开发23 分钟前
100w条数据丝滑滚动!Qt Model/View 架构实战(二)
开发语言·c++·qt
卓怡学长29 分钟前
w181springboot机场乘客服务系统
java·数据库·spring boot·spring·intellij-idea
萧瑟余晖1 小时前
Java深入解析篇三十九之集成测试
java·开发语言·集成测试
skr爱码士1 小时前
06_Qt 常用数据类型与容器:QString、QList、QVector、QMap 的性能与实现分析
开发语言·c++·qt
总有刁民想爱朕ha1 小时前
零基础Python开发「图片批量转MP4视频」工具,本地离线、免费无水印
开发语言·python·音视频
l1t1 小时前
测试DuckDB luajit插件读取本地通达信文件
开发语言·数据库·duckdb
老一岁1 小时前
c问题总结(2)
c语言·开发语言
Ming_studying1 小时前
Python批量压缩图片:支持JPG_PNG_WebP、尺寸限制与CSV报告
开发语言·图像处理·python·pillow·图片压缩
风月说与山鬼1 小时前
JS闭包详解
开发语言·javascript
何以解忧,唯有..1 小时前
Python协程详解:从生成器到async/await的完整指南
开发语言·python