public class ExcelFactory{private static final String EXCEL_FONT_FAMILY_SETTING = "Monaco"; //设置字体private static final int EXCEL_FONT_SIZE_SETTING = 12; //设置字体大小private WritableWorkbook writableWorkbook = null;private WritableSheet writableSheet = null;publicWritableWorkbook createExcel(OutputStream os, Excel excel,
List header, List datas, ExcelMappermapper)throwsRowsExceededException, WriteException { //生成exceltry{
writableWorkbook=Workbook.createWorkbook(os);
writableSheet=writableWorkbook.createSheet(excel.getSheetName(),
excel.getSheetNum());
SheetSettings settings=writableSheet.getSettings();
settings.setVerticalFreeze(1);//Write the title
if (header != null && header.size() > 0) {for (int i = 0; i < header.size(); i++) {
writableSheet.addCell(new Label(i, 0, header.get(i),
setHeaderCellStyle(newCellStyle(EXCEL_FONT_FAMILY_SETTING, EXCEL_FONT_SIZE_SETTING))));
}
}//Write data to file
if (datas != null && datas.size() > 0) {for (int i = 1; i <= datas.size(); i++) {
mapper.mapToExcel(writableSheet, datas.get(i- 1),
setBodyCellStyle(newCellStyle(EXCEL_FONT_FAMILY_SETTING, EXCEL_FONT_SIZE_SETTING)), i);
}
}
}catch(IOException e) {return null;
}returnwritableWorkbook;
}private WritableCellFormat setHeaderCellStyle(CellStyle style) throwsWriteException {
WritableFont font= newWritableFont(
WritableFont.createFont(style.getFont()), style.getFontSize(), WritableFont.BOLD);
WritableCellFormat cellFormat=setCentre(style, font);returncellFormat;
}private WritableCellFormat setBodyCellStyle(CellStyle style) throwsWriteException {
WritableFont font= newWritableFont(
WritableFont.createFont(style.getFont()), style.getFontSize(), WritableFont.NO_BOLD);
WritableCellFormat cellFormat=setCentre(style, font);returncellFormat;
}privateWritableCellFormat setCentre(CellStyle style, WritableFont font)throwsWriteException {
WritableCellFormat cellFormat= newWritableCellFormat(font);
cellFormat.setBackground(style.getBgColor());
cellFormat.setAlignment(Alignment.CENTRE);
cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);returncellFormat;
}
}