利用Java反射实现通用的Excel报表

最近有很多客户报表需要提供客户下载,需要生成一个Excel的格式文件,所以写了
一个通用的Excel报表生成代码供各个地方使用:
	public <T> void createExcelReport(List<T> reports,Map<String,String> headerMap,OutputStream output) throws IOException {
		if(reports == null || reports.isEmpty()) return;
		
		Workbook wb = new HSSFWorkbook();
		HSSFSheet sheet = (HSSFSheet) wb.createSheet("报表");
		HSSFRow row = sheet.createRow(0);
		
		//create header
		Object report = reports.get(0);
		Field[] fields = report.getClass().getDeclaredFields();
		for(int i = 0; i < fields.length; i++){
			String headValue = headerMap.get(fields[i].getName());
			row.createCell(i).setCellValue(headValue);
			sheet.setColumnWidth(i, 20 * 256);
		}
		
		//fill the data
		for(int i = 0; i < reports.size(); i++){
			Object rp = reports.get(i);
			row = sheet.createRow(i+1);
			for(int j = 0; j < fields.length; j++){
				String getMethodName = "get" + StringUtils.capitalize(fields[j].getName());
				Method method = null;
				try {
					method = rp.getClass().getMethod(getMethodName, null);
				}catch(NoSuchMethodException e){//for boolean type isField
					getMethodName = "is" + StringUtils.capitalize(fields[j].getName());
					try {
						method = rp.getClass().getMethod(getMethodName, null);
					} catch (Exception ex){
						throw new RuntimeException("Create Report failed!",ex);
					}
				}
				if(method != null){
					Object value;
					try {
						value = method.invoke(rp);
						value = value == null ? "" : value;
						row.createCell(j).setCellValue(value.toString());
					} catch (Exception e) {
						throw new RuntimeException("Create Report failed!",e);
					}
				}
			}
		}
		wb.write(output);
	}

你可能感兴趣的:(java,Excel,J#)