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();
        }
    }
}
相关推荐
是Smoky呢几秒前
springAI+向量数据库+RAG入门案例
java·开发语言·ai编程
huabiangaozhi11 分钟前
修改表字段属性,SQL总结
java·数据库·sql
请为小H留灯13 分钟前
一键解决 IDEA 中 Java 项目变橙色的问题!!!
java·ide·maven·intellij-idea·java项目
小文大数据31 分钟前
python实现HTML转PDF
java·前端·数据库
_Twink1e32 分钟前
[算法竞赛]九、C++标准模板库STL常用容器大全
开发语言·c++
架构师沉默36 分钟前
为什么 Dubbo 从 ZooKeeper 转向 Nacos?
java·后端·架构
用户83071968408241 分钟前
Spring Prototype Bean的四种正确使用方式
java·spring boot·后端
永恒_顺其自然44 分钟前
Java Web 传统项目异步分块上传系统实现方案
java·开发语言·前端
bu_shuo1 小时前
c++中对数组求和
开发语言·c++
赫瑞1 小时前
Java中的大数处理 —— BigInteger
java·开发语言