java表格下载

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@RestController
public class ExcelDownloadApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExcelDownloadApplication.class, args);
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadExcel() throws IOException {
        List<User> userList = getUsers(); // 获取要导出的数据

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 使用EasyExcel生成Excel文件
        ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        excelWriter.write(userList, writeSheet);
        excelWriter.finish();

        byte[] excelBytes = outputStream.toByteArray();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "users.xlsx");

        // 返回文件响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(excelBytes);
    }

    private List<User> getUsers() {
        // 模拟获取要导出的数据
        List<User> userList = new ArrayList<>();
        userList.add(new User("John", "Doe"));
        userList.add(new User("Jane", "Smith"));
        return userList;
    }

    public static class User {
        private String firstName;
        private String lastName;

        public User(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        // 省略getter和setter方法
    }
}

上述代码使用Spring Boot创建了一个简单的Web应用程序,并提供了一个用于表格下载的GET接口 /download。在接口的实现中,首先获取要导出的数据(这里使用了getUsers方法模拟获取数据)。然后,使用EasyExcel库生成Excel文件,并将生成的字节数组作为响应返回。

在生成Excel文件时,使用ExcelWriterWriteSheet进行配置,这里只创建了一个Sheet,命名为"Sheet1",并将数据写入其中。可以根据需要进行更多的配置,例如设置表头、样式等。

请确保在实际使用时,根据需要调整代码中的数据获取逻辑和Excel文件的配置。同时,确保在项目的依赖管理中包含EasyExcel库的正确版本。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值