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>
实体类
@Data
public class ExcelOV {
@Excel(name = "姓名")
private String name;
@Excel(name = "年龄")
private Integer age;
@Excel(name = "生日",format = "yyyy-MM-dd")
private Date date;
@Excel(name = "性别",replace={"男_true","女_false"})
private Boolean sex;
@Excel(name = "性别2",replace={"男男_0","女女_1"})
private Integer sex2;
}
1.后台下载方式
后台代码:
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExcelOV.class, excelOVList);
File file = new File("C:\\test.xls");
if (file.exists()) {
//判断文件的存在性
if (file.isDirectory()) {
System.out.println("文件存在!");
} else {
file.createNewFile();//创建文件
System.out.println("文件不存在,创建文件成功!");
}
} else {
File tmpFile = new File(file.getParent());
tmpFile.mkdirs();
if (file.isDirectory()) {
System.out.println("文件存在!");
} else {
file.createNewFile();//创建文件
System.out.println("文件不存在,创建文件成功!");
}
}
//保存数据
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
2.前台下载方式
后台接口:
/**
* 导出Excel
* @param response
*/
@RequestMapping(value = "/export", method = RequestMethod.POST)
public void export(HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExcelOV.class, excelOVList);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
}
前台代码:
<a id="test" href="javascript: ">下载Excel</a>
<script>
$(document).on('click', '#test', function (e) {
var xmlResquest = new XMLHttpRequest();
xmlResquest.open("POST", "后台接口路径", true);
xmlResquest.setRequestHeader("Content-type", "APPLICATION/OCTET-STREAM");
xmlResquest.responseType = "blob";
xmlResquest.onload = function (oEvent) {
var content = xmlResquest.response;
var elink = document.createElement('a');
elink.download = "test.xlsx";
elink.style.display = 'none';
var blob = new Blob([content]);
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
};
xmlResquest.send();
});
</script>