由于ajax請求不能下載坐慰,故先利用ajax將請求數(shù)據(jù)提交到后臺,存入redis囱皿,并返回一個uuid蔼囊,然后在ajax請求成功之后用window.location.href進行下載。
另外因為需求原因映凳,Excel列數(shù)和列title是動態(tài)的胆筒,所以利用反射創(chuàng)建工作簿。
HSSFWorkbook wb = CreateExcelByReflect.createWb(data);//創(chuàng)建工作簿
String fileName ="任務(wù)表" +new Date().getTime() +".xls";
OutputStream out =null;
try {
out = response.getOutputStream();
response.reset();
response.setHeader("Content-Disposition","attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName,"UTF-8"))));
response.setContentType("application/ms-excel;charset=UTF-8");
wb.write(out);
out.flush();
out.close();
}catch (IOException e) {
e.printStackTrace();
}
public class CreateExcelByReflect {
private static HSSFSheetsheet;//表格對象
private static HSSFWorkbookwb;//工作簿
private static LinkedHashMapheader;//表頭
//初始化
public static void init(String sheetName,JSONArray titleArr) {
wb =new HSSFWorkbook();
sheet =wb.createSheet(sheetName);
header =new LinkedHashMap();
for(Object title : titleArr){
JSONObject obj = (JSONObject) JSON.toJSON(title);
header.put(obj.getString("key"), obj.getString("title"));
}
}
/**
* 創(chuàng)建各列表頭
*/
public static void createHeadRow(){
HSSFRow head =sheet.createRow(0);//創(chuàng)建表格第一行對象诈豌,為表頭行
Iterator> headTitle =header.entrySet().iterator();//循環(huán)輸出表頭
for(int i=0;headTitle.hasNext();i++){
HSSFCell cell = head.createCell(i);
cell.setCellValue(headTitle.next().getValue());
}
}
/**
* 創(chuàng)建數(shù)據(jù)行
*/
public static void createRows(List data){
int rowCount = data.size();//根據(jù)數(shù)據(jù)集設(shè)置行數(shù)
for(int i=0;i
HSSFRow row =sheet.createRow(i+1);//創(chuàng)建行仆救,表頭是第0行
//轉(zhuǎn)換數(shù)據(jù),將每一個DO映射為屬性名與FieldsEntity的Map
Map map = DataConvertUtil.convertObjectToMap(data.get(i));
Iterator> head =header.entrySet().iterator();
//創(chuàng)建每行的單元格并填充值
for(int col =0;col
HSSFCell cell = row.createCell(col);
//設(shè)置表頭的迭代器
Map.Entry enty = (Map.Entry)head.next();
String name = enty.getKey();
Object value = map.get(name);
if(null != value){
cell.setCellValue(map.get(name).getValue().toString());//填充屬性值
}
}
}
}
public static HSSFWorkbook createWb(String sheetName,JSONArray titleArr, List data){
init(sheetName, titleArr);
createHeadRow();
createRows(data);
return wb;
}
}
public class DataConvertUtil {
/**
* 將對象的屬性名稱與值映射為MAP
* @param o 對象
* @return Mapkey為屬性名稱队询,value為名稱派桩、類型和值組成的對象
*/
public static Map convertObjectToMap(Object o){
Class oClass = o.getClass();
// Field[] fields = oClass.getDeclaredFields(); //獲取類中的所有聲明的屬性
Field[] fields =getBeanFields(oClass, oClass.getDeclaredFields());
Map map =new HashMap();
try{
for(int i=0;i
// 不對序列化ID進行映射
if(fields[i].getName().equals("serialVersionUID")){
continue;
}
Object valueObject =getFieldValue(o,fields[i].getName());
map.put(fields[i].getName(),new FieldsEntity(fields[i].getName(), valueObject, fields[i].getType()));
}
return map;
}catch(Exception e){
e.printStackTrace();
}
return map;
}
public static Field[] getBeanFields(Class cls,Field[] fs){
fs = (Field[]) ArrayUtils.addAll(fs, cls.getDeclaredFields());
if(cls.getSuperclass()!=null){
Class clsSup = cls.getSuperclass();
fs =getBeanFields(clsSup,fs);
}
return fs;
}
/**
* 通過對象的getter方法獲取屬性值
* @param o 對象
* @param name 屬性名稱
* @return 相應(yīng)屬性的值
*/
public static Object getFieldValue(Object o,String name)throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InvocationTargetException {
Class owner = o.getClass();
Method mothed = owner.getMethod(createGetter(name));
Object object = mothed.invoke(o);
return object;
}
/**
* 通過屬性名稱拼湊getter方法
* @param fieldName
* @return
*/
public static String createGetter(String fieldName){
if(fieldName ==null || fieldName.length() ==0 ){
return null;
}
StringBuffer sb =new StringBuffer("get");
sb.append(fieldName.substring(0,1).toUpperCase()).append(fieldName.substring(1));
return sb.toString();
}
}
public class FieldsEntity {
private StringattributeName;//屬性變量名稱
private Objectvalue;//屬性變量值
private ClassclassType;//屬性類型
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Class getClassType() {
return classType;
}
public void setClassType(Class classType) {
this.classType = classType;
}
public FieldsEntity(String fieldName, Object o, Class classType){
this.attributeName = fieldName;
this.value = o;
this.classType = classType;
}
}