import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.test.utils.ListUtil;
import com.test.utils.LogUtil;
public class MyExcelUtil {
private static final LogUtil logger = LogUtil.getLogUtil(MyExcelUtil.class);
/**
*
* <p>Title: newExportExcel</p>
*
* <p>Description: 导出excel方法:支持多数据自动分页</p>
*
* @param poClass
* @param dataMap key为sheetName的list,value为对应的数据
* @param fieldTags
* @param fields
* @param out
* @param dateFmtStr
* @return
*
*/
@SuppressWarnings("unused")
public static <T> boolean newExportExcel(Class<?> poClass, Map<String,List<T>> dataMap, String[] fieldTags, String[] fields,OutputStream out
, String dateFmtStr) {
isValidate(fieldTags, fields);
Class<?> c = poClass;
Map<String, PropertyDescriptor> pdMap = new HashMap<String, PropertyDescriptor>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(c);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
pdMap.put(pd.getName(), pd);
}
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
Sheet oldSheet = null;
WritableWorkbook wwb = null;
WritableSheet ws = null;
boolean isOK = false;
try {
wwb = Workbook.createWorkbook(out);
// 创建表头
WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);
WritableCellFormat wcfFC = new WritableCellFormat(wfc);
//wcfFC.setWrap(true);//根据长度自动换行
//多个结果集
for (Map.Entry<String, List<T>> entry:dataMap.entrySet()) {
String sheetName = entry.getKey();
List<T> results = entry.getValue();
logger.info("【newExportExcel】:【开始】sheetName={0};size={1}",sheetName,results.size());
//50000个一次
//List<List<T>> numList = ListUtil.partition(results, 100);//数据少时,测试使用
List<List<T>> numList = ListUtil.partition(results, 50000);//TODO
int i=0;
for (List<T> list : numList) {
String sheetName_i=sheetName;
if (i>0) {
sheetName_i=sheetName+"("+i+")";
}
i++;
logger.info("【newExportExcel】:【分批开始】sheetName={0};size={1}",sheetName_i,list.size());
isOK=setListToExcel(list, fieldTags, fields, dateFmtStr, sheetName_i, pdMap, oldSheet, wwb, wcfFC);
logger.info("【newExportExcel】:【分批结束】sheetName={0};size={1};res={2}",sheetName_i,list.size(),isOK);
//Thread.sleep(1000);//休眠1秒
}
}
} catch (Exception e) {
logger.error("【newExportExcel】:发生异常!{0}",e.getMessage());
} finally {
if (wwb != null) {
try {
wwb.write();
wwb.close();
} catch (Exception e) {
logger.error("【newExportExcel】:关闭流发生异常!{0}",e.getMessage());
}
}
}
return isOK;
}
//将list数据存进表格
public static <T> Boolean setListToExcel(List<T> results, String[] fieldTags, String[] fields, String dateFmtStr, String sheetName, Map<String, PropertyDescriptor> pdMap,
Sheet oldSheet, WritableWorkbook wwb, WritableCellFormat wcfFC) throws Exception {
WritableSheet ws;
int startRow = 0;
if (null==oldSheet) {
int sheets = wwb.getSheets().length;
if (sheets != 0) {
sheets += 1;
}
ws = wwb.createSheet(sheetName, sheets);
for (int i = 0; i < fieldTags.length; i++) {
Label label = new Label(i, 0, fieldTags[i], wcfFC);
ws.addCell(label);
}
startRow = 1;
} else {
ws = wwb.getSheet(sheetName);
startRow = oldSheet.getRows();
}
for (int row = startRow, i = 0; i < results.size(); i++, row++) {
T t = results.get(i);
for (int k = 0; k < fields.length; k++) {
PropertyDescriptor pd = pdMap.get(fields[k]);
Method method = pd.getReadMethod();
Object valueObj = method.invoke(t);
if (pd.getPropertyType() == Date.class) {
SimpleDateFormat fmt = new SimpleDateFormat(dateFmtStr);
if (valueObj != null) {
valueObj = fmt.format(valueObj);
}
}
if (null == valueObj) {
valueObj = "null";
}
Label label = new Label(k, row, valueObj.toString());
ws.addCell(label);
}
}
return true;
}
private static void isValidate(String[] fieldTags, String[] fields) {
/*if (!file.getName().endsWith(".xls")) {
throw new RuntimeException(file.getName() + " 文件必须是xls文件");
}*/
if (fieldTags.length != fields.length) {
throw new RuntimeException("字段名称数量和字段数量不匹配");
}
}