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;
	}

猜你喜欢

转载自blog.csdn.net/DavidSoCool/article/details/81539104