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文件时,使用ExcelWriter
和WriteSheet
进行配置,这里只创建了一个Sheet,命名为"Sheet1",并将数据写入其中。可以根据需要进行更多的配置,例如设置表头、样式等。
请确保在实际使用时,根据需要调整代码中的数据获取逻辑和Excel文件的配置。同时,确保在项目的依赖管理中包含EasyExcel库的正确版本。