说明:公共方法中可以在任何场景下进行Excel导出,使用的参数通用使用 List<Bean> 的格式,另外还执行在一个Excel中导出多个sheet (解决大数据导出的问题),需要注意的是如果使用03的方式导出一个sheet 最大只能有65535条记录,不然就会报错,使用07导出不存在这种限制!请根据实际情况进行选择。
具体如何调用请看最下面的调用实例。
一:公共方法函数
/**
*
* @param <T>
* 应用泛型,代表任意一个符合javabean风格的类
*/
public class ExportExcelUtil<T>
{
private Logger logger = Logger.getLogger(this.getClass());
/**
* excel 03 导出excel调用方法
*/
public void exportExcel(HSSFWorkbook workbook, int sheetNum,
String fileName, String[] headers, Collection<T> dataset,
OutputStream out)
{
exportExcel(workbook, sheetNum, fileName, headers, dataset, out,
"yyyy-MM-dd");
}
/**
* excel 07 导出excel调用方法
*/
public void exportExcel07(XSSFWorkbook workbook, int sheetNum,
String fileName, String[] headers, Collection<T> dataset,
OutputStream out)
{
exportExcel07(workbook, sheetNum, fileName, headers, dataset, out,
"yyyy-MM-dd");
}
/**
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*/
private void exportExcel07(XSSFWorkbook workbook, int sheetNum, String title,
String[] headers, Collection<T> dataset, OutputStream out,String pattern)
{
try
{
// 生成一个表格
XSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(sheetNum, title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 25);
// 生成一个样式
XSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++)
{
XSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
XSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Class<? extends Object> tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (null == value)
{
textValue = null;
} else
{
if (value instanceof Date)
{
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else
{
textValue = value.toString();
}
}
if (textValue != null)
{
cell.setCellValue(textValue);
}
}
}
} catch (IllegalAccessException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (InvocationTargetException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (SecurityException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (NoSuchMethodException e)
{
logger.error("导出:" + title + "报表出错!", e);
}
}
/**
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*/
@SuppressWarnings("deprecation")
private void exportExcel(HSSFWorkbook workbook, int sheetNum, String title,
String[] headers, Collection<T> dataset, OutputStream out,
String pattern)
{
try
{
// 生成一个表格
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(sheetNum, title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 25);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++)
{
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext())
{
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++)
{
HSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Class<? extends Object> tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (null == value)
{
textValue = null;
} else
{
if (value instanceof Date)
{
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else
{
textValue = value.toString();
}
}
if (textValue != null)
{
cell.setCellValue(textValue);
}
}
}
} catch (IllegalAccessException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (InvocationTargetException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (SecurityException e)
{
logger.error("导出:" + title + "报表出错!", e);
} catch (NoSuchMethodException e)
{
logger.error("导出:" + title + "报表出错!", e);
}
}
}
二:调用函数:
我下面的例子是一个Excel中包含多个sheet(按照统计日期来分割),具体写法需要根据具体的业务。原理是一样的。
如:
String title = "在线明细报表";
String[] headers = { "NUBE号 ", "统计日期 " };
String fileName = java.net.URLEncoder.encode(title, "utf-8") + "(" + startDay
+ " - " + endDay + ")";
response.reset();
response.setCharacterEncoding("gb2312");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename="
+ fileName + ".xls");
// 声明一个工作薄
OutputStream outputStream = response.getOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
ExportExcelUtil<DayInlineDetailBean> exportExcel = new ExportExcelUtil<DayInlineDetailBean>();
int i = 0;
for (Map.Entry<String, List<DayInlineDetailBean>> entry : returnMap
.entrySet())
{
exportExcel.exportExcel(workbook, i, entry.getKey(),
headers, entry.getValue(), outputStream);
i++;
}
try
{
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e)
{
logger.error("导出:" + title + "报表出错!", e);
}