1. 程式人生 > >java jxl實現通用匯出excel

java jxl實現通用匯出excel

包:jxl-2.6.12.jar、commons-beanutils-1.9.3.jar

/**
* @Description: TODO 通用模板
* @Title: writeToFile  
* @return void 
* @parm list 資料集合
* @parm nameList 屬性名和列名陣列集合,eg:[["attribute1","屬性名稱1"],["attribute2","屬性名稱2"]]
*/
public <T> void writeToFile(List<T> list, List<String[]> nameList, HttpServletResponse response) {

		if (CollectionUtils.isEmpty(nameList)) {
			return;
		}
        int FIRST_ROW = 0;
		try {
			WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
			// 建立一個工作表。
			WritableSheet sheet = book.createSheet("資料", 0);
			// 在工作表上面新增內容
			try {
				// 第一行新增標題
				Label label = null;
				for (int column = 0; column < nameList.size(); column++) {
                    // new Label(column, row, String.valueOf(contTheText));
					label = new Label(column, FIRST_ROW, nameList.get(column)[1]);
					sheet.addCell(label);
				}

				if (!CollectionUtils.isEmpty(list)) {
					Object param = null;
					for (int row = FIRST_ROW + 1; row <= list.size(); row++) {
						T t = list.get(row - 1);
						Map<String, Object> properties = conversionToMap(t);
						for (int i = 0; i < nameList.size(); i++) {
							param = properties.get(nameList.get(j)[0]);
							label = new Label(i, row, objectToString(param));
							sheet.addCell(label);
						}
					}
				}
			} catch (RowsExceededException e) {
				logger.error("行或列引數錯誤!{}", e);
			} catch (WriteException e) {
				logger.error("寫入失敗!{}", e);
			} catch (Exception e) {
				logger.error("寫入失敗!{}", e);
			} finally {
				if (book != null) {
					book.write();
					try {
						book.close();
					} catch (WriteException e) {
						logger.error("檔案關閉失敗!{}", e);
					}
				}
			}
		} catch (IOException e) {
			logger.error("建立檔案失敗!{}", e);
		}
	}
/**
*泛型轉換為map
*/
private <T> Map<String, Object> conversionToMap(T bean) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
		PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(bean);

		for (PropertyDescriptor d : descriptors) {
			String fieldName = d.getName();
			Object value = propertyUtilsBean.getNestedProperty(bean, fieldName);
			if (!"class".equals(fieldName))
				map.put(fieldName, value);
		}
		return map;
	}
/**
*onject轉string
*/
private String objectToString(Object param) {
		String value = "";
		if (param instanceof Number) {
            // 自定義取2位小數
			Double processResu = MoneyCalculate.round(new Double(param.toString()));
			value = processResu.toString();
		} else if (param instanceof String) {
			value = (String) param;
		} else if (param instanceof Boolean) {
			boolean b = ((Boolean) param).booleanValue();
			if (b) {
				value = "是";
			} else {
				value = "否";
			}
		} else if (param instanceof Date) {
            // 自定義時間轉換
			value = DateUtil.formatDateYMDHMS((Date) param);
		}
		return value;
	}