public class ExportExcelUtil {
/**
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中并且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上
*
* @param title
* 表格標題名
* @param headers
* 表格屬性列名數組
* @param dataset
* 需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。此方法支持的
* javabean屬性的數據類型有基本數據類型及String,Date,byte[](圖片數據)
* @param fieldNames
* 傳入的對應headers屬性列名數組的具體的字段名稱,javabean風格,模式如:model.user.name
* @param out
* 與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網絡中
* @param pattern
* 如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*/
public void exportExcel(String title, String[] headers,String[] fieldNames,List dataset, OutputStream out, String pattern) {
headers=this.addString("序號", 0, headers);
int column=headers.length;
HSSFWorkbook hwb = POIExcelUtil.createWorkbook();// 創建一個excel工作單
HSSFSheet hs=hwb.createSheet(title);
HSSFPatriarch patriarch = hs.createDrawingPatriarch();
// 定義注釋的大小和位置,詳見文檔
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0, 0, 0, (short) 4, 2, (short) 6, 5));
comment.setString(new HSSFRichTextString("提示:數據為單頁數據!"));
comment.setAuthor("liuhonglai");
hs.addMergedRegion(new CellRangeAddress(0, (short) 0, 0,(short) (column - 1))); // 合并單元格
int listSize = dataset!=null?dataset.size():0;
int rows = listSize + 2;// 定義總的行數
for (int i = 0; i < rows; i++) {// 循環創建行數
HSSFRow hr = POIExcelUtil.createRow(i, hs);// 根據查詢的數據在sheet中創建行
for (int j = 0; j < column; j++) {// 循環列數
HSSFCell hc = POIExcelUtil.createCell(j, hr);// 創建列
if (i == 0) {// 控制第一行的樣式
HSSFCellStyle cs = POIExcelUtil.createCellStyle(hwb);
HSSFFont font = POIExcelUtil.createFont(hwb);
font.setFontHeightInPoints((short) 14);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cs.setFont(font);// 設置字體
cs.setWrapText(true);
cs.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下邊框
cs.setBorderLeft(HSSFCellStyle.BORDER_NONE);// 左邊框
cs.setBorderRight(HSSFCellStyle.BORDER_NONE);// 右邊框
cs.setBorderTop(HSSFCellStyle.BORDER_NONE);// 上邊框
cs.setAlignment(CellStyle.ALIGN_CENTER);// 設置水平對齊方式
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 設置垂直對齊方式
StringBuffer buffer = new StringBuffer();
buffer.append(title);
POIExcelUtil.setSheetTitle(hs, cs, hr, hc, buffer.toString()); // 設置標題
break;
}
if (i == 1) {// 控制第二行的樣式,并設置列的名稱
HSSFCellStyle cs = POIExcelUtil.createCellStyle(hwb);
hr.setHeightInPoints((float) 24);
HSSFFont font = POIExcelUtil.createFont(hwb);
cs.setFont(font);// 設置字體
cs.setAlignment(CellStyle.ALIGN_CENTER);
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 設置單元格背景
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
hc.setCellType(HSSFCell.CELL_TYPE_STRING);
hc.setCellStyle(cs);
hc.setCellValue(headers[j]);
} else {// 設置內容
if(dataset!=null){
switch (j) {
case 0: //序號
hc.setCellValue(i - 1);
break;
default:
Object t= dataset.get(i - 2);// 去掉前兩行
if(j==2||j==3){
hs.setColumnWidth((int) j, (int) (35.7 * 150));
}else{
hs.setColumnWidth((int) j, (int) (35.7 * 80));
}
String fieldName =fieldNames[j-1];
Object value=null;
// String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
// Class tCls = t.getClass();
// try {
// Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
// value = getMethod.invoke(t, new Object[] {});
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
value = getColumnValue(t, fieldName);
String textValue = null;
if (value instanceof Integer) {
int intValue =( (Integer) value).intValue();
textValue=String.valueOf(intValue);
} else if (value instanceof Float) {
float fValue = ((Float) value).floatValue();
textValue=String.valueOf(fValue);
} else if (value instanceof Double) {
double dValue =( (Double) value).doubleValue();
textValue=String.valueOf(dValue);
} else if (value instanceof Long) {
long longValue =( (Long) value).longValue();
textValue=String.valueOf(longValue);
}else if (value instanceof Boolean) {
boolean bValue = ((Boolean) value).booleanValue();
textValue=String.valueOf(bValue);
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有圖片時,設置行高為60px;
hr.setHeightInPoints(60);
// 設置圖片所在列寬度為80px,注意這里單位的一個換算
hs.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, i-1, (short) 6, i-1);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, hwb.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// 其它數據類型都當作字符串簡單處理
if(value==null){
textValue="";
}else{
textValue = value.toString();
}
}
hc.setCellValue(textValue);
break;
}
}
}
}
}
POIExcelUtil.setPrintSetup(hwb, hs, rows, column);
try {
hwb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 遞歸方式處理.
* @param obj 傳入的對象
* @param fileNames 有層級javabean方式,model.user.name
* @return Object 值
* @author david
*/
private static Object getColumnValue(Object obj,String fieldNames){
if(null != fieldNames && !"".equals(fieldNames)){
try {
Object objVal = null;
int sp = fieldNames.indexOf(".");
String fieldName = "";
String afterFieldNames = "";
if(sp == -1){
fieldName = fieldNames;
}else{
fieldName = fieldNames.substring(0,sp);
afterFieldNames = fieldNames.substring(sp + 1,fieldNames.length());
}
String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
Class classz = obj.getClass();
Method getMethod;
getMethod = classz.getMethod(getMethodName,new Class[] {});
objVal = getMethod.invoke(obj, new Object[] {});
if(StringUtils.isBlank(afterFieldNames)){
return objVal;
}else{
return getColumnValue(objVal, afterFieldNames);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
private String[] addString(String str,int index,String[] old){
String[] temp=new String[old.length+1];
System.arraycopy(old, 0, temp, 0, old.length);
for(int i=old.length;i>index;i--){
temp[i]=temp[i-1];
}
temp[index]=str;
return temp;
}
}
posted on 2010-12-02 15:45
David1228 閱讀(425)
評論(0) 編輯 收藏