poi mysql 导出 excel乱码_将数据库中的数据导出为excel表格——java学习笔记

最近我的项目增加了一个需求,需要将数据库中的数据导出到excel表格中,再下载下来。而生成Excel比较有名的框架有Apache poi等,网络上介绍其使用方法的文章也很多,但是我今天使用的是阿里出的easyexcel框架,我个人感觉使用起来更简单便捷,GitHub地址

导入maven依赖

com.alibaba

easyexcel

2.1.1

导出excel

entity对象类

@Data

public class TabExcelProperty {

//设置excel表头名称

@ExcelProperty(value = "用户id",index = 0)

private Integer id;

@ExcelProperty(value = "用户名",index = 1)

private String name;

@ExcelProperty(value = "年龄",index = 2)

private Integer age;

@ExcelProperty(value = "性别",index = 3)

private String sex;

@ExcelProperty(value = "手机电话",index = 4)

private String phone;

}

value表示列的名称,index表示是第几列。

数据库中表的数据

9861dec7b0d5

在这里插入图片描述

Service类

@Service

public class ExportServiceImpl implements ExportService{

@Autowired

ExportMapper exportMapper;

@Override

public void exportExcel(HttpServletResponse response) {

//查询表中的数据

List list = exportMapper.getUser();

try {

response.setContentType("application/vnd.ms-excel");

response.setCharacterEncoding("utf-8");

// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系

String fileName = URLEncoder.encode("测试文件", "UTF-8").replaceAll("\\+", "%20");

response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

EasyExcel.write(response.getOutputStream(), TabExcelProperty.class).sheet("表格1").doWrite(list);

} catch (IOException e) {

e.printStackTrace();

}

}

}

通过mapper的exportMapper.getUser()方法查询出数据表中的数据,然后用EasyExcel.write写入响应对象中。

9861dec7b0d5

在这里插入图片描述

然后Controller直接调用就行。

结果:

9861dec7b0d5

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值