一、导入依赖
<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>4.4.0</version> </dependency>
二、pojo(根据实际需求写)
@Data @ExcelTarget("Data") public class Data implements Serializable { @Excel(name="状态",width = 10,orderNum="0") private String state; @Excel(name = "账号",orderNum="1") private String userAccount; @Excel(name = "密码",orderNum="2") private String userPsw; @Excel(name = "创建人",width = 15,orderNum="3") private String userName; @Excel(name = "创建时间",width = 25, format = "yyyy-MM-dd hh:MM:ss ",orderNum="4") private String createTime;
三、mapper(根据实际需求写)
@Mapper public interface DataExportDao { List<Data> findAlls(); }
四、mapper.xml(根据实际需求写)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xxxxxxxx.mapper.DataDao"> <!--查询数据--> <select id="findAlls" resultType="Data"> select state, userAccount, userPsw, userName, createId from data; </select>
五、service
public interface DataExportService { List<Data> findBanks(); }
六、serviceImpl
@Slf4j @Service public class DataExportServiceImpl implements DataExportService { @Autowired DataExportDao dataExportDao ; @Override public List<Data> findAlls() { List<Data> datas= dataExportDao .findAlls(); System.out.println(datas); return datas; }
七、controller
@Slf4j
@RestController
@RequestMapping("/data")
public class DataExportController {
@Autowired
DataExportService dataExportService ;
@GetMapping("/exportDatas")
public void exportDatas(HttpServletResponse response) throws IOException {
List<Data> list = dataExportService .findAlls();
ExportParams params = new ExportParams("Data", "Data", ExcelType.HSSF);
Workbook workbook = ExcelExportUtil.exportExcel(params, Data.class, list);
ServletOutputStream outputStream = null;
try {
response.setHeader("content-type", "application/octet-stream");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode( Data+".xls","UTF-8"));
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outputStream) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}