maven仓库:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta5</version></dependency>
</dependencies>
后台代码:
/**
* 导出Excel
*/
@RequestMapping("/exportMsg")
@ResponseBody
public int exportMsg(@RequestParam("codeId") Long codeId ,HttpServletResponse response) {
int r = 0;
try {
List exportAuthUsers = authenBusinessService.findByExportInviteCode(codeId);
OutputStream out = response.getOutputStream();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
String fileName= URLEncoder.encode("客户列表","utf-8");//设置导出格式
response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
ExcelUtil.writer(out,"人员列表",exportAuthUsers, ExportAuthUser.class);
out.flush();
r=1;
} catch (IOException e) {
e.printStackTrace();
}
return r;
}
后台工具类:
/**
* 导出Excel
* @param out Servlet 流
* @param sheetName sheet名称
* @param data 数据
* @param clazz 对应数据Class
*/
public static void writer(OutputStream out, String sheetName, List<? extends BaseRowModel> data,Class<? extends BaseRowModel> clazz){
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
Sheet sheet1 = new Sheet(1, 0, clazz);
sheet1.setSheetName(sheetName);
sheet1.setAutoWidth(Boolean.TRUE);
writer.write(data,sheet1);
writer.finish();
}
前台请求(不能使用ajax请求):
$('#outExcel').click(function(){
var codeIds = $("#codeIds").val();
window.location.href = '${ctx}/datas/exportMsg?codeId='+codeIds;
}