excel导出两级表头实现(poi)
java代码
@Getter
@Setter
public class ExcelHelper<T> {
/**
* 表格标题
*/
private String title;
/**
* 单元格宽度
*/
private int colWidth = 20;
/**
* 行高度
*/
private int rowHeight = 20;
private HSSFWorkbook workbook;
/**
* 表头样式
*/
private HSSFCellStyle headStyle;
/**
* 主体样式
*/
private HSSFCellStyle bodyStyle;
/**
* 日期格式化,默认yyyy-MM-dd HH:mm:ss
*/
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Constructor
* @param title
*/
public ExcelHelper(String title){
this.title = title;
workbook = new HSSFWorkbook();
init();
}
/**
* Constructor
* @param title
* @param colWidth
* @param rowHeight
*/
public ExcelHelper(String title, int colWidth, int rowHeight){
this.colWidth = colWidth;
this.rowHeight = rowHeight;
this.title = title;
workbook = new HSSFWorkbook();
init();
}
/**
* Constructor
* @param title
* @param colWidth
* @param rowHeight
* @param dateFormat
*/
public ExcelHelper(String title, int colWidth, int rowHeight, String dateFormat) {
this.title = title;
this.colWidth = colWidth;
this.rowHeight = rowHeight;
workbook = new HSSFWorkbook();
sdf = new SimpleDateFormat(dateFormat);
init();
}
/**
* 导出Excel,适用于web导出excel
*
* @param sheet
* @param data
*/
private void writeSheet(HSSFSheet sheet, List<T> data,List<Column> headerList) {
try {
sheet.setDefaultColumnWidth(colWidth);
sheet.setDefaultRowHeightInPoints(rowHeight);
createHead(headerList, sheet);
writeSheetContent(headerList, data, sheet);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 导出表格
* @param listColumn
* @param datas
* @return
* @throws Exception
*/
public InputStream exportExcel(List<Column> listColumn,List<T> datas) throws Exception {
splitDataToSheets(datas,listColumn);
return save(workbook);
}
/**
* 导出表格 支持2级表头或单表头的Excel导出
* @param headers
* @param datas
* @param filePath
* @throws FileNotFoundException
* @throws IOException
* void
*/
public void exportExcel(List<Column> headers,List<T> datas,String filePath) throws IOException {
splitDataToSheets(datas, headers);
save(workbook, filePath);
}
/**
* 把数据写入到单元格
* @param listColumn
* @param datas
* @param sheet
* @throws Exception
* void
*/
private void writeSheetContent(List<Column> listColumn,List<T> datas,HSSFSheet sheet) throws Exception {
HSSFRow row;
List<Column> listCol = getColumnList(listColumn);
for (int