xsl2

public HSSFWorkbook createWorkookByHean(String sheetName,
String[] titles,
HBean[] hBeans,
String[] beanColumns) throws IOException,ServiceException {
List<HashMap<String, Object>> hList = new ArrayList<HashMap<String, Object>>();
//转换成hashmap
HashMap<String, Object> map =null;
Object colValue =null;
for(HBean bean:hBeans){
map = new HashMap<String, Object>();
for(String column:beanColumns){
colValue = bean.getPropertyValue(column);
map.put(column, colValue);
}
hList.add(map);
}
return createWorkbook(sheetName,titles,hList,beanColumns);
}


public HSSFWorkbook createWorkbook(String sheetName,
String[] titles,
List<HashMap<String,Object>> list,
String[] mapKeys) throws IOException {
int sheetPages = (list.size()-1)/SHEETMAXROWS+1;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFFont font = wb.createFont();
HSSFCellStyle style = wb.createCellStyle();
font.setCharSet(HSSFCell.ENCODING_UTF_16);
style.setFont(font);

List<HashMap<String,Object>> curList = null;
for(int i=1;i<=sheetPages;i++) {// 只有一张sheet
HSSFSheet sheet = wb.createSheet(sheetName+"_"+i);
HSSFRow row = sheet.createRow(0);
// 填写Excel的表头
for (int m = 0; m < titles.length; m++) {
HSSFCell cell = row.createCell((short) m);
cell.setCellValue(titles[m]);
}

if(i*SHEETMAXROWS<=list.size()){
curList = list.subList((i-1)*SHEETMAXROWS, i*SHEETMAXROWS);
}else{
curList = list.subList((i-1)*SHEETMAXROWS, list.size());
}

//保存到excel
insertExcelRows(sheet,1,curList,mapKeys,style);
}
return wb;
}

/**
* 写入Excel数据行
* @param sheet:excel的页签对象
* @param list:数据列表,List中是数组,每个数组的数据按序来写入Excel。
* @param mapKeys List中是数组 的hashmap对象的key name,按excel的列的顺序列出
* @return
*/
private void insertExcelRows(HSSFSheet sheet,
int beginRow,
List<HashMap<String, Object>> list,
String[] mapKeys,HSSFCellStyle style) {

if (list == null)
return;

for (int i = 0; i < list.size(); i++) {
HashMap<String, ?> colMap = (HashMap<String, ?>) list.get(i);
if (colMap == null)
continue;
HSSFRow row = sheet.createRow(beginRow+i);
HSSFCell cell = null;
for (int j = 0; j < mapKeys.length; j++) {
Object obj = colMap.get(mapKeys[j]);
cell = row.createCell((short)j);
cell.setCellStyle(style);

if(obj instanceof Date){
String temp = DateTimeUtil.getDateFormat((Date)obj);
cell.setCellValue(temp);
}else if(obj instanceof Calendar) {
String temp = DateTimeUtil.getDateFormat(((Calendar)obj).getTime());
cell.setCellValue(temp);
//cell.setCellValue((Calendar)obj);
}else if(obj instanceof String){
cell.setCellValue((String)obj);
}else if(obj instanceof Number){
cell.setCellValue(((Number)obj).doubleValue());
}else if(obj instanceof Boolean){
cell.setCellValue((Boolean)obj);
}else{
cell.setCellValue(String.valueOf(obj));
}
}
}

}

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