通过传入实体类数组和指定导出列来即可,导出excel,读者可直接复制到项目直接使用,下面只是个简单的示例提供参考
一、导出excel工具类代码
/**
* 导出实体类
* @param head 表头
* @param exportColumn 导出字段
* @param exportList 实体数组
* @param clazz 实体类
* @return
* @throws Exception
*/
public SXSSFWorkbook export(String[] head,String[] exportColumn,List exportList,Class clazz) throws Exception{
XSSFWorkbook wb = new XSSFWorkbook ();
SXSSFWorkbook swb=new SXSSFWorkbook(wb,1000);
//swb.createSheet()
//创建第一个sheet(页),命名为 new sheet
SXSSFSheet sheet = null;
sheet = (SXSSFSheet) swb.createSheet("myData");
//创建head
SXSSFRow heqadrow = sheet.createRow(0);
int headlen = head.length;
for(int i=0;i<headlen;i++) {
heqadrow.createCell(i).setCellValue(head[i]);
}
//获取导出列
List<String> columnNameList = new ArrayList<String>();
if(exportColumn!=null&&exportColumn.length>0) {
int columnNameLen = exportColumn.length;
for(int i=0;i<columnNameLen;i++){
columnNameList.add(exportColumn[i]);
}
} else {//通过反射获取所有列
//暂未实现
System.err.println("请指明导出列");
}
//导出列
int exportListLen = exportList.size();
List<Method> methodList = new ArrayList<Method>();
int columnNameListLen = columnNameList.size();
for(int i=0;i<columnNameListLen;i++){
String methodName= "get".concat(captureName(columnNameList.get(i).toLowerCase()));
Method method = clazz.getMethod(methodName);
methodList.add(method);
}
for(int i=1;i<=exportListLen;i++){
Object entity = exportList.get(i-1);
SXSSFRow row = sheet.createRow(i);
for(int j=0;j<columnNameListLen;j++) {
Object value = methodList.get(j).invoke(entity);
if(value!=null) {
row.createCell(j).setCellValue(value.toString());
}
}
}
//写入文件
/*FileOutputStream fos = new FileOutputStream("e:\\txt.xls");
swb.write(fos);
fos.flush();*/
return swb;
}
二、导出excel的controller下载部分
SXSSFWorkbook wb = eu.export(head, exportColumn, easyJson.getRows(), TReportyszxqk.class);
OutputStream output=response.getOutputStream(); //response为springMVC传入的httpservletResponse
response.reset();
response.setHeader("Content-disposition", "attachment; filename=details.xls");
response.setContentType("application/msexcel");
wb.write(output);
output.close();
三、前端下载部分
1.html
<form action="exportYszx" style="display:none" id="downForm" method="post">
</form>
<button id="btn_export"> 导出</button>
2.js
$("#btn_export").click(function(){
$("#downForm").empty();
for(var key in searchData){
var input = "<input name='"+key+"'value='"+searchData[key]+"'>";
$("#downForm").append(input)
}
$("#downForm").submit();
})