第一步:在pom文件中导入如下依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
第二步:在实体需要导出的字段上面添加如下注解
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
-------导包
@Excel(name = "配置项值") ----excel表头名
@TableField("PRIMARILY") ----数据库中的字段名
第三步代码
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
public void getKeyList(HttpServletResponse response) throws IOException {
try {
Random random = new Random();
int i = random.nextInt(10000);
List<grantConfig> keyList = grantConfigMapper.getKeyList();
//导出文件前先备份一份到服务器上
//格式化获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//文件存放的路径
String fileName = "E:\\granConfig";
//文件名称
String path = fileName + "\\UNV8_GRANT_CONFIG" + sdf.format(new Date()) + "(" + i + ")" + ".xls";
System.out.println(path);
//如果没有文件,就创建出来
File file = new File(fileName);
if (!file.exists()) {
file.mkdirs();
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), grantConfig.class, keyList);
//获取字节输出流,把内存中的数据输出到硬盘保存
FileOutputStream fos = new FileOutputStream(new File(path));
workbook.write(fos);
//自己下载一份
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=UNV8_GRANT_CONFIG.xls");
workbook.write(response.getOutputStream());
//关闭资源
fos.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
按钮
<a href="/grantConfig/exportGrantFile" class="layui-btn" id="exportFile"
style="margin-top: 1%; margin-right: 1%; float: right;">
<i class="layui-icon">导出</i>
</a>