package com.meiliwan.emall.stock.bean;

/**
* User: wuzixin
* Date: 13-12-5
* Time: 下午3:28
*/
public class ExcelColumn {
/**
* 索引
*/
private int index;

/**
* 字段名称
*/
private String fieldName;

/**
* 字段显示名称
*/
private String fieldDispName;

/**
* 字段类型
*/
private int type;

public ExcelColumn() {

}

public ExcelColumn(int index, String fieldName, String fieldDispName) {
super();
this.index = index;
this.fieldName = fieldName;
this.fieldDispName = fieldDispName;
}

public ExcelColumn(int index, String fieldName, String fieldDispName, int type) {
super();
this.index = index;
this.fieldName = fieldName;
this.fieldDispName = fieldDispName;
this.type = type;
}

public int getIndex() {
return index;
}

public String getFieldName() {
return fieldName;
}

public void setIndex(int index) {
this.index = index;
}

public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}

public String getFieldDispName() {
return fieldDispName;
}

public void setFieldDispName(String fieldDispName) {
this.fieldDispName = fieldDispName;
}

public int getType() {
return type;
}

public void setType(int type) {
this.type = type;
}

@Override
public String toString() {
return "ExcelColumn [fieldDispName=" + fieldDispName + ", fieldName="
+ fieldName + ", index=" + index + ", type=" + type + "]";
}
}

 

 

package com.meiliwan.emall.stock.bean;

import java.util.List;
import java.util.Map;

/**
* Created with IntelliJ IDEA.
* User: wuzixin
* Date: 13-12-5
* Time: 下午3:29
*/
public class ExcelHead {
/**
* 列信息
*/
private List<ExcelColumn> columns;

/**
* 需要转换的列
*/
private Map<String, Map> columnsConvertMap;

/**
* 头部所占用的行数
*/
private int rowCount;

/**
* 头部所占用的列数
*/
private int columnCount;

public List<ExcelColumn> getColumns() {
return columns;
}

public int getRowCount() {
return rowCount;
}

public int getColumnCount() {
return columnCount;
}

public void setColumns(List<ExcelColumn> columns) {
this.columns = columns;
}

public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}

public void setColumnCount(int columnCount) {
this.columnCount = columnCount;
}

public Map<String, Map> getColumnsConvertMap() {
return columnsConvertMap;
}

public void setColumnsConvertMap(Map<String, Map> columnsConvertMap) {
this.columnsConvertMap = columnsConvertMap;
}

@Override
public String toString() {
return "ExcelHead [columnCount=" + columnCount + ", columns=" + columns
+ ", columnsConvertMap=" + columnsConvertMap + ", rowCount="
+ rowCount + "]";
}

}

 

package com.meiliwan.emall.stock.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
* User: wuzixin
* Date: 13-12-5
* Time: 下午4:05
*/
public class BeanUtil {
/**
* 将一个 Map 对象转化为一个 JavaBean
*
* @param type 要转化的类型
* @param map 包含属性值的 map
* @return 转化出来的 JavaBean 对象
* @throws java.beans.IntrospectionException
* 如果分析类属性失败
* @throws IllegalAccessException 如果实例化 JavaBean 失败
* @throws InstantiationException 如果实例化 JavaBean 失败
* @throws java.lang.reflect.InvocationTargetException
* 如果调用属性的 setter 方法失败
*/
@SuppressWarnings("rawtypes")
public static Object populateBean(Object type, Map map) {
BeanInfo beanInfo = null; // 获取类属性
Object obj = null; // 创建 JavaBean 对象
try {
beanInfo = Introspector.getBeanInfo(type.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
try {
obj = type.getClass().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();

if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
}
}
return obj;
}


public static Object getProperty(Object bean, String property) {
Class<?> beanClass = bean.getClass();
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(
beanClass, property);

Method readMethod = propertyDescriptor.getReadMethod();
try {
return readMethod.invoke(bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}

private static PropertyDescriptor getPropertyDescriptor(Class<?> beanClass,
String propertyname) {
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(beanClass);
} catch (IntrospectionException e) {
e.printStackTrace();
}
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
PropertyDescriptor propertyDescriptor = null;
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor currentPropertyDescriptor = propertyDescriptors[i];
if (currentPropertyDescriptor.getName().equals(propertyname)) {
propertyDescriptor = currentPropertyDescriptor;
}

}
return propertyDescriptor;
}
}

 

package com.meiliwan.emall.stock.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.meiliwan.emall.commons.util.StringUtil;
import com.meiliwan.emall.stock.bean.ExcelColumn;
import com.meiliwan.emall.stock.bean.ExcelHead;

import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
* Created with IntelliJ IDEA.
* User: wuzixin
* Date: 13-12-5
* Time: 下午3:31
*/
public class ExcelHelper {

/**
* Excel助手类
*
* @createTime: 2012-4-19 上午10:14:46
* @version: 0.1
* @lastVersion: 0.1
* @updateTime:
* @changesSum:
*/
private static ExcelHelper helper = null;

private ExcelHelper() {

}

public static synchronized ExcelHelper getInstanse() {
if (helper == null) {
helper = new ExcelHelper();
}
return helper;
}

/**
* 将Excel文件导入到list对象
*
* @param head 文件头信息
* @param file 导入的数据源
* @param cls 保存当前数据的对象
* @return List
*/
public List importToObjectList(ExcelHead head, File file, Class cls) {
List contents = null;
FileInputStream fis;
// 根据excel生成list类型的数据
List<List> rows;
try {
fis = new FileInputStream(file);
rows = excelFileConvertToList(fis);

// 删除头信息
for (int i = 0; i < head.getRowCount(); i++) {
rows.remove(0);
}
Map<String, Integer> paramsType = getPropertType(head);
// 将表结构转换成Map
Map<Integer, String> excelHeadMap = convertExcelHeadToMap(head.getColumns());
// 构建为对象
contents = buildDataObject(excelHeadMap, head.getColumnsConvertMap(), rows, cls, paramsType);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return contents;
}

/**
* 导出数据至Excel文件
*
* @param modelFile 模板Excel文件
* @param outputFile 导出文件
* @param dataList 导入excel报表的数据来源
* @return void
*/
public void exportExcelFile(ExcelHead head, File modelFile, File outputFile, List<?> dataList) {
// 读取导出excel模板
InputStream inp = null;
Workbook wb = null;
try {
inp = new FileInputStream(modelFile);
wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
// 生成导出数据
buildExcelData(sheet, head, dataList);

// 导出到文件中
FileOutputStream fileOut = new FileOutputStream(outputFile);
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (InvalidFormatException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* 将报表结构转换成Map
*
* @param excelColumns
* @return void
*/
private Map<Integer, String> convertExcelHeadToMap(List<ExcelColumn> excelColumns) {
Map<Integer, String> excelHeadMap = new HashMap<Integer, String>();
for (ExcelColumn excelColumn : excelColumns) {
if (StringUtil.checkNull(excelColumn.getFieldName())) {
continue;
} else {
excelHeadMap.put(excelColumn.getIndex(), excelColumn.getFieldName());
}
}
return excelHeadMap;
}

/**
* 生成导出至Excel文件的数据
*
* @param sheet 工作区间
* @param dataList 导入excel报表的数据来源
* @return void
*/
private void buildExcelData(Sheet sheet, ExcelHead head, List<?> dataList) {
List<ExcelColumn> excelColumns = head.getColumns();
Map<String, Map> excelHeadConvertMap = head.getColumnsConvertMap();

// 将表结构转换成Map
Map<Integer, String> excelHeadMap = convertExcelHeadToMap(excelColumns);

// 从第几行开始插入数据
int startRow = head.getRowCount();
int order = 1;
for (Object obj : dataList) {
Row row = sheet.createRow(startRow++);
for (int j = 0; j < excelColumns.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellType(excelColumns.get(j).getType());
String fieldName = excelHeadMap.get(j);
if (fieldName != null) {
Object valueObject = BeanUtil.getProperty(obj, fieldName);

// 如果存在需要转换的字段信息,则进行转换
if (excelHeadConvertMap != null && excelHeadConvertMap.get(fieldName) != null) {
valueObject = excelHeadConvertMap.get(fieldName).get(valueObject);
}

if (valueObject == null) {
cell.setCellValue("");
} else if (valueObject instanceof Integer) {
cell.setCellValue((Integer) valueObject);
} else if (valueObject instanceof String) {
cell.setCellValue((String) valueObject);
} else if (valueObject instanceof Date) {
Date date = (Date) valueObject;
cell.setCellValue(date.getTime());
} else {
cell.setCellValue(valueObject.toString());
}
} else {
cell.setCellValue(order++);
}
}
}
}

/**
* 将Excel文件内容转换为List对象
*
* @param fis excel文件
* @return List<List>
* @throws IOException
*/
public List<List> excelFileConvertToList(FileInputStream fis) throws Exception {
Workbook wb = WorkbookFactory.create(fis);

Sheet sheet = wb.getSheetAt(0);

List<List> rows = new ArrayList<List>();
for (Row row : sheet) {
List<Object> cells = new ArrayList<Object>();
for (Cell cell : row) {
Object obj = null;

CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
obj = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
obj = (Date) cell.getDateCellValue();
} else {
obj = cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
obj = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
obj = cell.getNumericCellValue();
break;
default:
obj = null;
}
cells.add(obj);
}
rows.add(cells);
}
return rows;
}

/**
* 根据Excel生成数据对象
*
* @param excelHeadMap 表头信息
* @param excelHeadConvertMap 需要特殊转换的单元
* @param rows
* @param cls
* @return void
* 2012-4-18 上午11:39:43
* @auther <a href="mailto:hubo@feinno.com">hubo</a>
*/
private List buildDataObject(Map<Integer, String> excelHeadMap, Map<String, Map> excelHeadConvertMap, List<List> rows, Class cls, Map<String, Integer> paramsTypes) {
List contents = new ArrayList();
for (List list : rows) {
// 如果当前第一列中无数据,则忽略当前行的数据
if (list == null || list.get(0) == null) {
break;
}
// 当前行的数据放入map中,生成<fieldName, value>的形式
Map<String, Object> rowMap = rowListToMap(excelHeadMap, excelHeadConvertMap, list, paramsTypes);

// 将当前行转换成对应的对象
Object obj = null;
try {
obj = cls.newInstance();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
obj = BeanUtil.populateBean(obj, rowMap);

contents.add(obj);
}
return contents;
}

/**
* 将行转行成map,生成<fieldName, value>的形式
*
* @param excelHeadMap 表头信息
* @param excelHeadConvertMap excelHeadConvertMap
* @param list
* @return Map<String,Object>
*/
private Map<String, Object> rowListToMap(Map<Integer, String> excelHeadMap, Map<String, Map> excelHeadConvertMap, List list, Map<String, Integer> paramsTypes) {
Map<String, Object> rowMap = new HashMap<String, Object>();
for (int i = 0; i < list.size(); i++) {
String fieldName = excelHeadMap.get(i);
// 存在所定义的列
if (fieldName != null) {
Object value = null;
if (paramsTypes.get(fieldName) == 1) {
value = Integer.parseInt(String.format("%.0f",list.get(i)));
}else {
value = list.get(i);
}
if (excelHeadConvertMap != null && excelHeadConvertMap.get(fieldName) != null) {
value = excelHeadConvertMap.get(fieldName).get(value);
}
rowMap.put(fieldName, value);
}
}
return rowMap;
}

/**
* 获取对应字段的类型,主要用于区别double,int等
*
* @param head
* @return
*/
private Map<String, Integer> getPropertType(ExcelHead head) {
List<ExcelColumn> list = head.getColumns();
Map<String, Integer> map = new HashMap<String, Integer>();
for (ExcelColumn column : list) {
if (!StringUtil.checkNull(column.getFieldName())) {
map.put(column.getFieldName(), column.getType());
}
}
return map;
}
}