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();
        }
    }
}
相关推荐
lly202406几秒前
TypeScript 运算符
开发语言
故事和你911 分钟前
洛谷-算法1-1-模拟与高精度2
开发语言·数据结构·c++·算法·动态规划
Cosmoshhhyyy3 分钟前
《Effective Java》解读第46条:优先选择Stream中无副作用的函数
java·windows·python
无籽西瓜a5 分钟前
【西瓜带你学设计模式 | 第十一期 - 模板方法模式】模板方法模式 —— 流程骨架与钩子实现、优缺点与适用场景
java·后端·设计模式·软件工程·模板方法模式
小樱花的樱花5 分钟前
C++权限对继承的影响
开发语言·c++
牛奔5 分钟前
g:Go 版本管理器安装与使用指南
开发语言·后端·golang
九皇叔叔8 分钟前
005-SpringSecurity-Demo 配置外部文件映射
java·springboot·文件·springsecurity
Gent_倪8 分钟前
Quartz 入门指南(二)Spring Boot + Quartz 示例
java·spring boot·quartz
唐不是营养物质10 分钟前
无头浏览器chromedriver使用(目前不支持国产操作系统)
java·pdf
Joy T13 分钟前
【Web3】NFT 元数据去中心化存储与智能合约集成实战
开发语言·web3·去中心化·区块链·php·智能合约·hardhat