1. The template may be regarded as two: header row, the first fixed column format
2. Example wrapper class:
/**
* 导出Excel
*/
public class ExportExcelTemplate1<T> {
/**
* @param title
* 表格标题
* @param headers
* 头部标题集合
* @param dataset
* 数据集合
* @param out
* 输出流
*/
public void exportExcel(String titleName, String[] rowHeaders, String[] cellHeaders,Collection<T> dataset, HttpServletResponse response) {
exportExcel2007(titleName, rowHeaders, cellHeaders,dataset, response, "yyyy-MM-dd HH:mm:ss");
}
/**
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
*/
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
public void exportExcel2007(String titleName, String[] rowHeaders, String[] cellHeaders,Collection<T> dataset, HttpServletResponse response,
String pattern) {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(titleName);
// 设置表格默认列宽度为15个字节
sheet.autoSizeColumn((short) 0);
// 生成一个样式
XSSFCellStyle style = workbook.createCellStyle();
// 设置背景色
style.setFillForegroundColor((short) 13);
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
// 设置边框
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
// 设置居中
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setColor(new XSSFColor(java.awt.Color.BLUE));
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 设置自动换行
style.setWrapText(true);
// 生成并设置另一个样式
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
XSSFFont font2 = workbook.createFont();
font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
XSSFCell cell;
for (int i = 0; i < rowHeaders.length; i++) {
cell = row.createCell(i + 1);// 标题行的单元格索引从1开始
cell.setCellStyle(style);
cell.setCellValue(new XSSFRichTextString(rowHeaders[i]));
}
//产生表格标题列
for (int j = 1; j <= cellHeaders.length; j++) {
XSSFRow rownum = sheet.createRow(j);
cell = rownum.createCell(0);//获取第一个单元格(首列)
cell.setCellStyle(style);
cell.setCellValue(new XSSFRichTextString(cellHeaders[j-1]));
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
// 反射类
Field[] fields;
Field field;
XSSFRichTextString richString;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher;
String fieldName;
String getMethodName;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = (T) it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
cell = row.createCell(i + 1);
cell.setCellStyle(style2);
field = fields[i];
fieldName = field.getName();
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
// 设置下载时客户端Excel的名称
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(titleName.getBytes(), "iso-8859-1") + ".xlsx");
OutputStream ouputStream = response.getOutputStream();
workbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Call wrapper class instance:
// 导出Excel
@RequestMapping(value = "/find", method = RequestMethod.GET)
@ResponseBody
public String ExportExcelInfo1(HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
//sheet名称
String[] titleName = "水文表";
// excel标题表头
String[] titles0 = { "1时", "2时", "3时", "4时", "5时", "6时", "7时", "8时", "9时", "10时", "11时", "12时", "13时", "14时",
"15时", "16时", "17时", "18时", "19时", "20时", "21时", "22时", "23时", "24时" };
String[] celles0 = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
// 调用封装类
ExportExcelTemplate2<User> util = new ExportExcelTemplate2<User>();
List<User> list = new ArrayList<User>();
util.exportExcel(titleName, titles0, celles0, list, "D://sheet.xls");
return "D://sheet.xls";
}