java代码如何使用poi导出excel到响应流中呢?

欢喜 Java经验 发布时间:2025-06-05 17:38:09 阅读数:13022 1
下文笔者将采用示例的方式,讲述导出excel到响应流中的方法及示例分享,如下所示
java中我们可采用Apache POI导出excel数据
    如下例所示

例:在Spring Boot中使用Apache POI导出 Excel 到响应流

1.添加 Maven 依赖(POI)

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version> <!-- 请根据需要选择版本 -->
</dependency>

2.编写Controller接口(导出 Excel)

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.list;

@RestController
@RequestMapping("/export")
public class ExcelExportController {

    @GetMapping("/excel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");

        // 创建 Workbook
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用户列表");

        // 表头
        Row headerRow = sheet.createRow(0);
        List<String> headers = Arrays.asList("ID", "姓名", "年龄", "邮箱");
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
        }

        // 模拟数据
        List<User> users = List.of(
            new User(1L, "张三", 25, "zhangsan@example.com"),
            new User(2L, "李四", 30, "lisi@example.com")
        );

        // 填充数据
        int rowNum = 1;
        for (User user : users) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId().toString());
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getAge());
            row.createCell(3).setCellValue(user.getEmail());
        }

        // 输出到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    // 用户实体类
    static class User {
        private Long id;
        private String name;
        private int age;
        private String email;

        public User(Long id, String name, int age, String email) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.email = email;
        }

        public Long getId() { return id; }
        public String getName() { return name; }
        public int getAge() { return age; }
        public String getEmail() { return email; }
    }
}

Apache POI代码注意事项

步骤 说明
设置响应类型 `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
设置文件名 `Content-Disposition: attachment; filename=xxx.xlsx`
使用 `XSSFWorkbook` 支持 `.xlsx` 格式(推荐);若需支持 `.xls`,
可用 `HSSFWorkbook`
写入响应流 `workbook.write(response.getOutputStream())`
关闭资源 `workbook.close()`避免内存泄漏
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202506/17491163228486.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者