alibaba开源框架easyexcel文件导出

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());
	 }
	}
}

到此,下载后端代码就结束了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值