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();
        }
    }
}
相关推荐
SL_staff17 分钟前
JVS数字底座实践:如何复用企业文档能力快速构建知识类应用
java·数据库·程序员
sugar__salt19 分钟前
MyBatis ③动态 SQL 完全指南 —— 从条件拼接到批量操作
java·sql·mybatis
吴声子夜歌20 分钟前
正则指引——PHP
开发语言·正则表达式·php
吃饱了得干活30 分钟前
Java并发安全:看这一篇就懂了!
java·后端·面试
前端双越老师32 分钟前
前端学习 Java 其实很容易:TS 和 Java 语法的 N 个相同点
java·全栈
Claire_8833 分钟前
企业文件管理系统选型技术框架与主流产品对比分析
开发语言·php
(Charon)40 分钟前
【C++】:使用 mutex + deque 实现一个简单的 LockedQueue
开发语言·c++
星轨初途1 小时前
LeetCode 热题 100——day10 和为 K 的子数组
开发语言·c++·算法·leetcode
sycmancia1 小时前
Qt——自定义控件温度计
开发语言·qt
农村小镇哥1 小时前
怎么把HTM格式转化成WORD
ui·c#·word