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();
        }
    }
}
相关推荐
Fuly1024几秒前
java面试知识点复习
java·开发语言·面试
郭涤生7 分钟前
std::condition_variable的使用及主要事项
开发语言·c++
小菜鸡桃蛋狗12 分钟前
C++——list
开发语言·c++
hopetomorrow21 分钟前
学习路之PHP --PHP 常用扩展及作用表
开发语言·学习·php
信徒_25 分钟前
API 网关技术选型
java
simple-L625 分钟前
Java开发痛点技术文章大纲
java·开发语言
gc_229929 分钟前
学习C#调用OpenXml操作word文档的基本用法(27:学习文本运行类-续)
word·openxml·run·runproperties
m0_6356474837 分钟前
Qt打包含有第三方库的软件为应用程序——CQtDeployer
开发语言·数据库·qt
simple-L644 分钟前
Vue3 前端开发技术文章大纲
开发语言
南宫萧幕1 小时前
Python与Simulink联合仿真:基于DQN的HEV能量管理策略建模与全链路排雷实战
开发语言·人工智能·python·算法·机器学习·matlab·控制