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();
        }
    }
}
相关推荐
Chase_Mos3 小时前
Spring 必会之微服务篇(1)
java·spring·微服务
码上淘金3 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo3 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
格林威5 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
小林学习编程5 小时前
SpringBoot校园失物招领信息平台
java·spring boot·后端
撸码到无法自拔5 小时前
docker常见命令
java·spring cloud·docker·容器·eureka
橙子199110165 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
androidwork5 小时前
Kotlin Android LeakCanary内存泄漏检测实战
android·开发语言·kotlin
heart000_15 小时前
IDEA 插件推荐:提升编程效率
java·ide·intellij-idea
学地理的小胖砸6 小时前
【Python 基础语法】
开发语言·python