springboot使用EasyExcel导出任意表数据
项目需求,输入表名,导出表数据
引入依赖`
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
<scope>compile</scope>
</dependency>
返回对象
/**
* @Author
* @Date 2023/9/21 10:53
* @CLassName PageParams
* @Description 查询返回对象
*/
@Data
@ApiModel
public class CommonResult<T> {
/**
* 状态码
*/
@ApiModelProperty(value = "状态码")
private String status;
/**
* 错误信息
*/
@ApiModelProperty(value = "错误信息")
private String errors;
/**
* 错误信息
*/
@ApiModelProperty(value = "错误信息")
private String message;
/**
* 结果数据
*/
@ApiModelProperty(value = "结果数据")
private T result;
public CommonResult() {
}
public CommonResult(String status, String errors, T result) {
this.status = status;
this.errors = errors;
this.result = result;
this.message = errors;
}
public static <T> CommonResult success(T result) {
return new CommonResult("000000", "success", result);
}
public static CommonResult fail(String errors) {
return new CommonResult("100000", errors, "");
}
public static CommonResult fail(String status, String errors) {
return new CommonResult(status, errors, "");
}
public static CommonResult fail(String fail, ResponseCodeEnum enumCode) {
return new CommonResult(String.valueOf(enumCode.getValue()), fail, "");
}
}
controller请求接口
/**
* 导出excel
*/
@CrossOrigin
@RequestMapping("/queryDate")
public CommonResult exportExcel(@RequestBody Map<String, String> params, HttpServletResponse response) throws IOException {
String tableName = params.get("tableName");
if (StringUtils.isEmpty(tableName)) {
return CommonResult.fail("表不能为空");
}
try {
List<Map> result = testOperateService.queryData(tableName);
if (CollectionUtils.isEmpty(result)) {
return CommonResult.fail("查询数据为空");
}
// 取表字段为表头
List<String> head = new ArrayList<>(result.get(0).keySet());
//数据
List<Object> data = new ArrayList<>();
data.add(head);
for (Map objData : result) {
data.add(objData.values());
}
String fileName = URLEncoder.encode("导出数据", "UTF-8").replaceAll("\\+", "%20");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename*=" + fileName + new Date() + ".xlsx");
response.flushBuffer();
EasyExcel.write(response.getOutputStream()).needHead(false).useDefaultStyle(false).automaticMergeHead(false).
sheet(tableName).doWrite(data);
} catch (Exception e) {
log.error("导出excel失败!【{}】", e);
}
return CommonResult.success("导出成功");
}
testOperateService#queryData查询数据,返回list
xml文件:
<select id="queryData" resultType="java.util.Map">
select * from ${tableName}
</select>