第一步:在pom文件中导入如下依赖
cn.afterturn
easypoi-base
3.2.0
cn.afterturn
easypoi-web
3.2.0
cn.afterturn
easypoi-annotation
3.2.0
第二步在实体需要导入的字段上面添加如下注解
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 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();
}
}
按钮
导出