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();
        }
    }
}
相关推荐
用户3721574261351 小时前
Java 将 Excel 图表导出为图片:指定图表、批量导出与图表工作表
java
炸膛坦客1 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
这个昵称不容易2 小时前
交流论坛网站设计与实现:SpringBoot 论坛 130 个接口,附论文与运行截图
java·springboot·毕设
夜不会漫长2 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David2 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
apcipot_rain3 小时前
C++转java日记(13)
java·开发语言
郝学胜-神的一滴3 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio4 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
星恒随风4 小时前
从0实现C++ AI大模型接入SDK(五):DeepSeekProvider的实现——策略模式、HTTP请求与SSE流式响应
linux·开发语言·c++·人工智能