easyexcel,web写入
时间: 2023-11-23 12:56:10 浏览: 69
写入excel数据
EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目,支持读取百万级别的Excel,同时支持多种方式写入Excel。下面是使用EasyExcel实现web写入Excel的步骤:
1.引入EasyExcel依赖
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
```
2.编写实体类
```java
@Data
public class DemoData {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private Integer age;
}
```
3.编写Controller
```java
@RestController
public class DemoController {
@PostMapping("/write")
public void writeExcel(HttpServletResponse response) throws IOException {
// 设置响应头
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
// 写入Excel
EasyExcel.write(response.getOutputStream(), DemoData.class).sheet("demo").doWrite(data());
}
private List<DemoData> data() {
List<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setName("张三" + i);
data.setAge(i);
list.add(data);
}
return list;
}
}
```
4.访问接口
访问`http://localhost:8080/write`,即可下载名为`demo.xlsx`的Excel文件,其中包含了10条数据。
阅读全文