天天看點

Java使用jxl導出Excel表格源碼

/**
	 * 導出Excel
	 * 
	 * @param list
	 *            :結果集合
	 * @param filePath
	 *            :指定的路徑名
	 * @param out
	 *            :輸出流對象 通過response.getOutputStream()傳入
	 * @param mapFields
	 *            :導出字段 key:對應實體類字段 value:對應導出表中顯示的中文名
	 * @param sheetName
	 *            :工作表名稱
	 */
	public static void createExcel(List list, String filePath,
			OutputStream out, Map<String, String> mapFields, String sheetName) {
		sheetName = sheetName != null && !sheetName.equals("") ? sheetName
				: "sheet1";
		WritableWorkbook wook = null;// 可寫的工作薄對象
		Object objClass = null;
		try {
			if (filePath != null && !filePath.equals("")) {
				wook = Workbook.createWorkbook(new File(filePath));// 指定導出的目錄和檔案名
																	// 如:D:\\test.xls
			} else {
				wook = Workbook.createWorkbook(out);// jsp頁面導出用
			}

			// 設定頭部字型格式
			WritableFont font = new WritableFont(WritableFont.TIMES, 10,
					WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.RED);
			// 應用字型
			WritableCellFormat wcfh = new WritableCellFormat(font);
			// 設定其他樣式
			wcfh.setAlignment(Alignment.CENTRE);// 水準對齊
			wcfh.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直對齊
			wcfh.setBorder(Border.ALL, BorderLineStyle.THIN);// 邊框
			wcfh.setBackground(Colour.YELLOW);// 背景色
			wcfh.setWrap(false);// 不自動換行

			// 設定内容日期格式
			DateFormat df = new DateFormat("yyyy-MM-dd HH:mm:ss");
			// 應用日期格式
			WritableCellFormat wcfc = new WritableCellFormat(df);

			wcfc.setAlignment(Alignment.CENTRE);
			wcfc.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直對齊
			wcfc.setBorder(Border.ALL, BorderLineStyle.THIN);// 邊框
			wcfc.setWrap(false);// 不自動換行

			// 建立工作表
			WritableSheet sheet = wook.createSheet(sheetName, 0);
			SheetSettings setting = sheet.getSettings();
			setting.setVerticalFreeze(1);// 當機視窗頭部

			int columnIndex = 0; // 列索引
			List<String> methodNameList = new ArrayList<String>();
			if (mapFields != null) {
				String key = "";
				Map<String, Method> getMap = null;
				Method method = null;
				// 開始導出表格頭部
				for (Iterator<String> i = mapFields.keySet().iterator(); i
						.hasNext();) {
					key = i.next();
					// 應用wcfh樣式建立單元格
					sheet.addCell(new Label(columnIndex, 0, mapFields.get(key),
							wcfh));
					// 記錄字段的順序,以便于導出的内容與字段不出現偏移
					methodNameList.add(key);
					columnIndex++;
				}
				if (list != null && list.size() > 0) {
					// 導出表格内容
					for (int i = 0, len = list.size(); i < len; i++) {
						objClass = list.get(i);
						getMap = getAllMethod(objClass);// 獲得對象所有的get方法
						// 按儲存的字段順序導出内容
						for (int j = 0; j < methodNameList.size(); j++) {
							// 根據key擷取對應方法
							method = getMap.get("GET"
									+ methodNameList.get(j).toString()
											.toUpperCase());
							if (method != null) {
								// 從對應的get方法得到傳回值
								String value = method.invoke(objClass, null).toString();
								// 應用wcfc樣式建立單元格
								sheet.addCell(new Label(j, i + 1, value, wcfc));
							} else {
								// 如果沒有對應的get方法,則預設将内容設為""
								sheet.addCell(new Label(j, i + 1, "", wcfc));
							}

						}
					}
				}
				 /** **********将以上緩存中的内容寫到EXCEL檔案中******** */ 
				wook.write();
				
				//System.out.println("導出Excel成功!");
			} else {
				throw new Exception("傳入參數不合法");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (wook != null) {
					wook.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * 擷取類的所有get方法
	 * 
	 * @param cls
	 * @return
	 */
	public static HashMap<String, Method> getAllMethod(Object obj)
			throws Exception {
		HashMap<String, Method> map = new HashMap<String, Method>();
		Method[] methods = obj.getClass().getMethods();// 得到所有方法
		String methodName = "";
		for (int i = 0; i < methods.length; i++) {
			methodName = methods[i].getName().toUpperCase();// 方法名
			if (methodName.startsWith("GET")) {
				map.put(methodName, methods[i]);// 添加get方法至map中
			}
		}
		return map;
	}
           
/**
	 * 根據指定路徑導出Excel
	 * 
	 * @param list
	 * @param filePath
	 * @param mapFields
	 * @param sheetName
	 */
	public static void ImportExcel(List list, String filePath,
			Map<String, String> mapFields, String sheetName) {
		createExcel(list, filePath, null, mapFields, sheetName);
	}

	/**
	 * 從Jsp頁面導出Excel
	 * 
	 * @param list
	 * @param filePath
	 * @param out
	 * @param mapFields
	 * @param sheetName
	 */
	public static void ImportExcel(List list, OutputStream out,
			Map<String, String> mapFields, String sheetName) {
		createExcel(list, null, out, mapFields, sheetName);
	}
           
public static void main(String[] args) {
		
		// 測試
		Store user = new Store();
		user.setName("張三");
		user.setAddress("德政北路");
		user.setTime(new Date());
		List<Store> list = new ArrayList<Store>();
		list.add(user); // 将user實體添加到list
		Map<String, String> map = new LinkedHashMap<String, String>();
		// 設定導出的字段。其中map中的key必須與實體類中的字段一緻,不區分大小寫,這裡需要注意的是:請確定實體類中給導出的字段提供了set、get方法,不然會取不到值
		map.put("name", "姓名");
		map.put("address", "位址");
		map.put("Time", "建立時間");
		ImportExcel(list, "E:\\xxsl\\test.xls", map, "員工資訊");
	}
           

效果圖:

Java使用jxl導出Excel表格源碼

JSP效果圖:

Java使用jxl導出Excel表格源碼

WEB環境下直接調用ImportExcel的方法就可以了。