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();
        }
    }
}
相关推荐
米糕闯编程2 分钟前
xshell使用CentOS10 root用户登录,权限问题
java·linux
sxhcwgcy4 分钟前
Python中的简单爬虫
java
小温冲冲8 分钟前
Qt WindowContainer 完整实战示例:QWidget 嵌入 QML
开发语言·数据库·qt
xiaoliuliu1234514 分钟前
Android Studio 2025 安装教程:详细步骤+自定义安装路径+SDK配置(附桌面快捷方式创建)
java·前端·数据库
老前端的功夫22 分钟前
【Java从入门到入土】21:List三剑客:ArrayList、LinkedList、Vector的爱恨情仇
java·javascript·网络·python·list
MyBFuture27 分钟前
Halcon条形码与二维码识别全攻略
开发语言·人工智能·halcon·机器视觉
SAP小崔说事儿29 分钟前
SAP B1 批量应用用户界面配置模板
java·前端·ui·sap·b1·无锡sap
电商API&Tina40 分钟前
唯品会数据采集API接口||电商API数据采集
java·javascript·数据库·python·sql·json
AI+程序员在路上42 分钟前
新手进入嵌入式行业方法与方向选择
c语言·开发语言·单片机·嵌入式硬件
dovens42 分钟前
GO 快速升级Go版本
开发语言·redis·golang