ExcelUtil.java 10.4 KB
package com.framework.excel;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;

import com.google.common.collect.Maps;

public class ExcelUtil<T> {

	private Class<T> clazz;

	public ExcelUtil(Class<T> clazz) {
		this.clazz = clazz;
	}

	public List<T> importExcel(String sheetName, InputStream input) {
		int maxCol = 0;
		List<T> list = new ArrayList<T>();
		try {
			HSSFWorkbook wb = new HSSFWorkbook(input);
			HSSFSheet sheet = null;
			if (!"".equals(sheetName.trim())) {
				sheet = wb.getSheet(sheetName);
			} else {
				sheet = wb.getSheetAt(0); // 如果不指定sheet名默认指向第一个sheet
			}
			int rows = sheet.getPhysicalNumberOfRows();
			if (rows > 0) {
				// 有数据时处理
				Field[] fields = clazz.getDeclaredFields();
				Map<Integer, Field> fieldsMap = Maps.newHashMap();
				for (Field field : fields) {
					if (field.isAnnotationPresent(ExcelAnnotation.class)) {
						ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
						int col = getExcelCol(attr.column());
						maxCol = Math.max(col, maxCol);
						field.setAccessible(true);
						fieldsMap.put(col, field);
					}
				}
				for (int i = 0; i < rows; i++) {
					HSSFRow row = sheet.getRow(i);
					int cellNum = maxCol;
					T entity = null;
					for (int j = 0; j < cellNum; j++) {
						HSSFCell cell = row.getCell(j);
						if (cell == null) {
							continue;
						}
						int cellType = cell.getCellType();
						String c = "";
						if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
							c = String.valueOf(cell.getNumericCellValue());
						} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
							c = String.valueOf(cell.getBooleanCellValue());
						} else {
							c = cell.getStringCellValue();
						}
						if (c == null || "".equals(c)) {
							continue;
						}
						entity = entity == null ? clazz.newInstance() : entity; // 如果不存在实例则新建.
						Field field = fieldsMap.get(j); // 从map中得到对应列的field.
						if (field == null) {
							continue;
						}
						// 取得类型,并根据对象类型设置值.
						Class<?> fieldType = field.getType();
						if (String.class == fieldType) {
							field.set(entity, String.valueOf(c));
						} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
							field.set(entity, Integer.parseInt(c));
						} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
							field.set(entity, Long.valueOf(c));
						} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
							field.set(entity, Float.valueOf(c));
						} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
							field.set(entity, Short.valueOf(c));
						} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
							field.set(entity, Double.valueOf(c));
						} else if (Character.TYPE == fieldType) {
							if ((c != null) && (c.length() > 0)) {
								field.set(entity, Character.valueOf(c.charAt(0)));
							}
						}
						if (entity != null) {
							list.add(entity);
						}
					}
				}
			}
			wb.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 对list数据源将其里面的数据导入到excel表单
	 * 
	 * @param sheetNames 工作表的名称
	 * @param output java输出流
	 */
	public boolean exportExcel(List<T>[] lists, String[] sheetNames, OutputStream output) {
		if (lists.length != sheetNames.length) {
			return false;
		}
		HSSFWorkbook workbook = new HSSFWorkbook(); // 产生工作薄对象
		HSSFCellStyle style = workbook.createCellStyle();
		for (int ii = 0; ii < lists.length; ii++) {
			List<T> list = lists[ii];
			String sheetName = sheetNames[ii];

			List<Field> fields = getMappedFiled(clazz, null, ExcelAnnotation.class);

			HSSFSheet sheet = workbook.createSheet(); // 产生工作表对象

			workbook.setSheetName(ii, sheetName);

			HSSFRow row;
			HSSFCell cell; // 产生单元格
			row = sheet.createRow(0); // 产生一行
			// 写入各个字段的列头名称
			for (int i = 0; i < fields.size(); i++) {
				Field field = fields.get(i);
				ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
				int col = getExcelCol(attr.column()); // 获得列号
				cell = row.createCell(col); // 创建列
				cell.setCellType(attr.cellType()); // 设置列中写入内容为String类型
				cell.setCellValue(attr.name()); // 写入列名

				// 如果设置了提示信息则鼠标放上去提示.
				if (!"".equals(attr.prompt().trim())) {
					setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, col, col); // 这里默认设了2-101列提示.
				}
				// 如果设置了combo属性则本列只能选择不能输入
				if (attr.combo().length > 0) {
					setHSSFValidation(sheet, attr.combo(), 1, 100, col, col); // 这里默认设了2-101列只能选择不能输入.
				}

				cell.setCellStyle(style);
			}

			int startNo = 0;
			int endNo = list.size();
			// 写入各条记录,每条记录对应excel表中的一行
			for (int i = startNo; i < endNo; i++) {
				row = sheet.createRow(i + 1 - startNo);
				T vo = (T) list.get(i); // 得到导出对象.
				for (int j = 0; j < fields.size(); j++) {
					Field field = fields.get(j); // 获得field.
					field.setAccessible(true); // 设置实体类私有属性可访问
					ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
					try {
						// 根据ExcelAnnotation中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
						if (attr.isExport()) {
							cell = row.createCell(getExcelCol(attr.column())); // 创建cell
							cell.setCellType(attr.cellType());
							if (attr.cellType() == 0) {
								cell.setCellValue(Double.parseDouble(field.get(vo).toString()));
							} else {
								cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
							}
						}
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}

		try {
			output.flush();
			workbook.write(output);
			workbook.close();
			output.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 对list数据源将其里面的数据导入到excel表单
	 * 
	 * @param sheetName 工作表的名称
	 * @param output java输出流
	 */
	@SuppressWarnings("unchecked")
	public boolean exportExcel(List<T> list, String sheetName, OutputStream output) {
		List<T>[] lists = new ArrayList[1];
		lists[0] = list;
		String[] sheetNames = new String[1];
		sheetNames[0] = sheetName;
		return exportExcel(lists, sheetNames, output);
	}

	/**
	 * 设置单元格上提示
	 * 
	 * @param sheet 要设置的sheet.
	 * @param promptTitle 标题
	 * @param promptContent 内容
	 * @param firstRow 开始行
	 * @param endRow 结束行
	 * @param firstCol 开始列
	 * @param endCol 结束列
	 * @return 设置好的sheet.
	 */
	public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) {
		// 构造constraint对象
		DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
		// 四个参数分别是:起始行、终止行、起始列、终止列
		CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
		// 数据有效性对象
		HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint);
		dataValidationView.createPromptBox(promptTitle, promptContent);
		sheet.addValidationData(dataValidationView);
		return sheet;
	}

	/**
	 * 
	 * @Title: setHSSFValidation
	 * @Description: 设置某些列的值只能输入预制的数据,显示下拉框.
	 * @param  sheet
	 * @param  textlist
	 * @param  firstRow
	 * @param  endRow
	 * @param  firstCol
	 * @param  endCol
	 * @param @return
	 * @return HSSFSheet
	 * @throws
	 */
	public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
		// 加载下拉列表内容
		DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
		// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
		CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
		// 数据有效性对象
		HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
		sheet.addValidationData(dataValidationList);
		return sheet;
	}

	/**
	 * 
	 * @Title: getExcelCol
	 * @Description: 将EXCEL中A,B,C,D,E列映射成0,1,2,3
	 * @param  col
	 * @param @return
	 * @return int
	 * @throws
	 */
	public static int getExcelCol(String col) {
		col = col.toUpperCase();
		// 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
		int count = -1;
		char[] cs = col.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
		}
		return count;
	}

	/**
	 * 得到实体类所有通过注解映射了数据表的字段
	 * 
	 * @param map
	 * @return
	 */
	@SuppressWarnings({"rawtypes", "unchecked" })
	private List<Field> getMappedFiled(Class clazz, List<Field> fields, Class annoclass) {
		if (fields == null) {
			fields = new ArrayList<Field>();
		}

		Field[] allFields = clazz.getDeclaredFields(); // 得到所有定义字段
		// 得到所有field并存放到一个list中.
		for (Field field : allFields) {
			if (field.isAnnotationPresent(annoclass)) {
				fields.add(field);
			}
		}
		if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
			getMappedFiled(clazz.getSuperclass(), fields, annoclass);
		}

		return fields;
	}
}