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();
        }
    }
}
相关推荐
覆东流6 分钟前
Java开发环境搭建
java·开发语言·后端
阿洛学长10 分钟前
VMware安装虚拟机教程(超详细)
java·linux·开发语言
rit843249910 分钟前
链路预测(Link Prediction)MATLAB 实现
开发语言·matlab
jiayong2310 分钟前
01 检查 Python 版本与环境
开发语言·python
coder Ethan13 分钟前
Spring AI 入门:(3)快速搭建一个简单的问答助手
java·人工智能·spring
屋外雨大,惊蛰出没16 分钟前
starter的创建与引用
java·stater
小同志0018 分钟前
Spring Boot ⽇志概述(简单了解)
java·java-ee·日志
小马爱打代码21 分钟前
SpringBoot + 延迟消息 + 时间轮:订单超时、优惠券过期等场景的高效实现方案
java·spring boot·后端
就叫_这个吧25 分钟前
Java普通类、抽象类、接口的应用和区别
java·开发语言
梅孔立28 分钟前
解决Nginx缓存不写入响应体问题:浏览器强制不缓存配置教程
java·开发语言·nginx·spring