jsp页面(导出按钮):
<button class="btn btn-primary layui-operation" type="button" id="downLoad" onclick="downLoadBtn()" style="margin-left:10px;">
<i class="fa fa-sign-out"></i> <span class="bold">导出</span>
</button>
ajax请求:
function downLoadBtn(){
window.location.href='${ctx}/quyu/administrativecode/sysArea/exportExcelTemplate'
}
controller:
@ResponseBody
@RequestMapping(value = "exportExcelTemplate")
public void exportExcelTemplate(SysArea sysArea, HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = "行政区划数据模板" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + ".xlsx";
//查询行政区划列表
List<SysArea> list = sysAreaService.findList(sysArea);
ExportExcel excelTemplate = new ExportExcel("行政区划数据", SysArea.class, 2).setDataList(list);
//导出
excelTemplate.write(response, fileName).dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
ExportExcel工具类:
/**
* 添加数据(通过annotation.ExportField添加数据)
* @return list 数据列表
*/
public <E> ExportExcel setDataList(List<E> list){
for (E e : list){
int colunm = 0;
Row row = this.addRow();
StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){
ExcelField ef = (ExcelField)os[0];
Object val = null;
// Get entity value
try{
if (StringUtils.isNotBlank(ef.value())){
val = Reflections.invokeGetter(e, ef.value());
}else{
if (os[1] instanceof Field){
val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
}else if (os[1] instanceof Method){
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
}
}
// If is dict, get dict label
if (StringUtils.isNotBlank(ef.dictType())){
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
}
}catch(Exception ex) {
// Failure to ignore
log.info(ex.toString());
val = "";
}
this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
sb.append(val + ", ");
}
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
}
return this;
}
/**
* 输出到客户端
* @param fileName 输出文件名
*/
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
response.setHeader("filename", Encodes.urlEncode(fileName));
write(response.getOutputStream());
return this;
}
/**
* 清理临时文件
*/
public ExportExcel dispose(){
wb.dispose();
return this;
}