alibaba开源框架easyexcel使用
官方文档:https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write
1. 下载
@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String test1;
@ExcelProperty("日期标题")
private Date date1;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/download")
public void download(HttpServletResponse response){
testService.downloadFile(response);
}
}
import com.alibaba.excel.EasyExcel;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
public class TestService {
public void downloadFile(HttpServletResponse response) throws IOException {
// 准备一些示例数据。
List<DemoData> data = new ArrayList<>();
DemoData demoData = new DemoData();
demoData.setTest1("测试1");
demoData.setDate1(new Date());
demoData.setDoubleData(15.20);
// 设置响应头信息以触发浏览器下载操作。
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
try (OutputStream outputStream = response.getOutputStream()) {
// 使用 EasyExcel 将准备好的数据写入输出流并生成 .xlsx 文件。
EasyExcel.write(outputStream, DemoData.class).sheet("Sheet1").doWrite(data);
} catch (IOException e) {
throw new RuntimeException("导出失败:" + e.getMessage());
}
}
}
到此,下载后端代码就结束了