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();
        }
    }
}
相关推荐
寒山李白40 分钟前
关于Java项目构建/配置工具方式(Gradle-Groovy、Gradle-Kotlin、Maven)的区别于选择
java·kotlin·gradle·maven
QX_hao1 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白1 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
无妄无望1 小时前
docker学习(4)容器的生命周期与资源控制
java·学习·docker
MC丶科2 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
千码君20162 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
跳动的喵尾巴3 小时前
Endnote | word中加载项消失不见,如何处理?
word
夜白宋3 小时前
【word多文档docx合并】
java·word
Evand J3 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
@yanyu6663 小时前
idea中配置tomcat
java·mysql·tomcat