springSSM 使用poi導出excel(一)

使用的核心知識爲java的反射機制,註解的使用,下面是過程代碼:java

一、js部分web

function exportExcelCom(actionurl){spring

var $form = $("<form>");   //定義一個form表單

$form.attr('style', 'display:none');   //在form表單中添加查詢參數

$form.attr('target', '');

$form.attr('method', 'post');

$form.attr('action', actionurl);

$('body').append($form);  //將表單放置在web中

    $form.submit();

}數據庫

二、spring Controllerapp

@RequestMapping(value = "/exportExcel")post

public void exportExcel(HttpServletRequest request,編碼

HttpServletResponse response) throws SecurityException,url

IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, Exception{.net

System.out.println("執行導出***");excel

byte[] fileNameByte = ("職業病基礎知識.xls").getBytes("GBK");    
    String filename = new String(fileNameByte, "ISO8859-1"); 
    List<ZywsptGfxwjb> list = new ArrayList<ZywsptGfxwjb>();
    /*ZywsptGfxwjb zywsptGfxwjb = new ZywsptGfxwjb();
    zywsptGfxwjb.setMc("名稱1");
    zywsptGfxwjb.setGjz("關鍵系");
    list.add(zywsptGfxwjb);*/
    list = gfxwjService.selectObjExist();
    byte[] bytes = excelService.export(list);
    response.setContentType("application/x-msdownload");    
    response.setContentLength(bytes.length);    
    response.setHeader("Content-Disposition", "attachment;filename="    
            + filename);    
    response.getOutputStream().write(bytes);
}

三、通用類方法

public static byte[] export(String sheet1, String title, Class<?> clazz,List<?> list) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, Exception{ ByteArrayOutputStream out = new ByteArrayOutputStream();

// 第一步,建立一個webbook,對應一個Excel文件    
    HSSFWorkbook wb = new HSSFWorkbook();

    // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet    
    HSSFSheet sheet = wb.createSheet(sheet1); 

    // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short  

    HSSFRow row = sheet.createRow((int) 0);

    // 第四步,建立單元格,並設置值表頭 設置表頭居中    
    HSSFCellStyle style = wb.createCellStyle();

    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式

    //設置表頭    
    List<ExportFiledsBean> excelHead = getExcelHead(clazz);
    String clazzName = clazz.getName();
    Class  _class = Class.forName(clazzName);
    
    HSSFCell cell = null;
    // excel頭    
    for (int i = 0; i < excelHead.size(); i++) {   
    	ExportFiledsBean exportFiledsBean = excelHead.get(i);
        cell = row.createCell(i);    
        cell.setCellValue(exportFiledsBean.getName());    
        cell.setCellStyle(style);
    }  
    
    for (int i = 0;i<list.size();i++)
    {
    	row = sheet.createRow((int) i + 1); 
    	Object obj = (Object) list.get(i);
    	for(int j=0;j<excelHead.size();j++)
    	{
    		ExportFiledsBean exportFiledsBean = excelHead.get(j);
    		String getFuncName = exportFiledsBean.getGetFuncName();
    		
    		Method addMethod = _class.getMethod(getFuncName);
    		Object result = addMethod.invoke(obj);
    		if(result==null)
    		{
    			row.createCell((int) j).setCellValue("");
    		}else{
    			row.createCell((int) j).setCellValue(result.toString());
    		}
    	}
    	
    }
    wb.write(out); 
    // 第五步,寫入實體數據 實際應用中這些數據從數據庫獲得
	return out.toByteArray();
}

private static List<ExportFiledsBean> getExcelHead(Class<?> clazz){

	return AunotationUtil.getExportFileds(clazz);

}

private void insertCell(HSSFRow row,int i,Object object){    

    if(object==null){    

        row.createCell(i).setCellValue("");    
            
    }else{    

        row.createCell(i).setCellValue(object.toString());    
            
    }    
        
}

四、註解方法解析類

public class AunotationUtil {

/**
 * 獲取註解的方法
 * [@param](https://my.oschina.net/u/2303379) clazz
 * [@return](https://my.oschina.net/u/556800)
 */
public static List<ExportFiledsBean> getExportFileds(Class<?> clazz){

	List<ExportFiledsBean> exportFiledsBeans = new ArrayList<ExportFiledsBean>();

	String clazzName = clazz.getName();

	//System.out.println("class的name:"+clazzName);

	Field[] fileds = clazz.getDeclaredFields();
	for(Field field :fileds)
	{
		if(field.isAnnotationPresent(ExportField.class))
		{
			ExportField exportField=(ExportField)field.getAnnotation(ExportField.class);
			String fieldName = field.getName();
			String name = exportField.name();
			String setFuncName = exportField.setFuncName();
			String getFuncName = exportField.getFuncName();
			boolean bl = exportField.isExport();
			
			ExportFiledsBean exportFiledsBean = new ExportFiledsBean();
			if(bl==true)
			{
				exportFiledsBean.setFiledName(fieldName);
				exportFiledsBean.setName(name);
				exportFiledsBean.setSetFuncName(setFuncName);
				exportFiledsBean.setGetFuncName(getFuncName);
				//System.out.println(fieldName+":"+name+":"+setFuncName+":"+getFuncName);
				exportFiledsBeans.add(exportFiledsBean);
			}
		}
	}
	
	return exportFiledsBeans;
}

public static void main(String[] arg)
{
	AunotationUtil.getExportFileds(ZywsptGfxwjb.class);
}

}

五、註解

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExportField {

public String name() default "filedName";
public String setFuncName() default "setField";
    public String getFuncName() default "getField";
    public boolean isExport() default false;

}

六、pojo類

public class ExportFiledsBean {

private String filedName;

private String name;

private String setFuncName;

private String getFuncName;

}

public class ZywsptGfxwjb {

@ExportField(name="編碼",setFuncName="setId",getFuncName="getId",isExport=false)
private BigDecimal id;

@ExportField(name="名稱",setFuncName="setMc",getFuncName="getMc",isExport=true)
private String mc;

@ExportField(name="關鍵字",setFuncName="setGjz",getFuncName="getGjz",isExport=true)
private String gjz;

}

相關文章
相關標籤/搜索