自己写的导出excel报表的公共方法,该公共方法主要用于非横向流动性报表导出
1.创立excel基本初始步骤
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle cellStyle = excelUtil.setHeaderStyle(wb);//表头格式
XSSFCellStyle cellStyle2 = excelUtil.setContentStyle(wb);//表体
XSSFSheet sheet = wb.createSheet("newsheet");
XSSFRow head = sheet.createRow(0);
2.创建表头格式方法
public XSSFCellStyle setHeaderStyle(XSSFWorkbook wb) {
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中
XSSFFont font = wb.createFont();
font.setFontName("宋体");
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); // 粗体显示
font.setFontHeightInPoints((short) 14);// 设置字体大小
cellStyle.setFont(font);// 选择需要用到的字体格式
return cellStyle;
}
3.创立表体格式公共方法
public XSSFCellStyle setContentStyle(XSSFWorkbook wb) {
XSSFCellStyle cellStyle2 = wb.createCellStyle();
cellStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyle2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中
XSSFFont font2 = wb.createFont();
font2.setFontName("宋体");
font2.setFontHeightInPoints((short) 12);
cellStyle2.setFont(font2);// 选择需要用到的字体格式
return cellStyle2;
}
4.在复合excel表中创立子表头样式公共方法
public XSSFCellStyle setSubHeaderStyle(XSSFWorkbook wb) {
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中
XSSFFont font = wb.createFont();
font.setFontName("仿宋_GB2312");
font.setColor(HSSFColor.GREY_50_PERCENT.index);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); // 粗体显示
font.setFontHeightInPoints((short) 13);// 设置字体大小
cellStyle.setFont(font);// 选择需要用到的字体格式
return cellStyle;
}
5.在复合excel表中创立子表体样式公共方法
public XSSFCellStyle setSubContentStyle(XSSFWorkbook wb) {
XSSFCellStyle cellStyle2 = wb.createCellStyle();
cellStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyle2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中
XSSFFont font2 = wb.createFont();
font2.setFontName("仿宋_GB2312");
font2.setColor(HSSFColor.GREY_50_PERCENT.index);
font2.setFontHeightInPoints((short) 11);
cellStyle2.setFont(font2);// 选择需要用到的字体格式
return cellStyle2;
}
6.创立表头内容公共方法
private String [] headers = {"姓名","学号","性别","班级","语文","数学","英语",
"物理","化学","生物","总分","排名"};
将初始步骤中创建的参数和表头传入此公共方法中
public void createHeadCell(String[] headArray,XSSFCellStyle cellStyle,XSSFRow row){
int count = 0;
for(int i=0;i<headArray.length;i++){
XSSFCell headcell = row.createCell(count);
headcell.setCellStyle(cellStyle);
headcell.setCellValue(headArray[i]);
count++;
}
}
7.创立表体内容公共方法
将每一行的表体插入一个list里,然后每创建一行掉一次该方法,list的内容要按表头顺序添加
//创立表体
public void createValueCell(List cellList, XSSFCellStyle cellStyle, XSSFRow row){
int count = 0;
for(int i=0;i<cellList.size();i++){
XSSFCell headcell = row.createCell(count);
headcell.setCellStyle(cellStyle);
if(cellList.get(i) == null){
headcell.setCellValue("");
count++;
continue;
}
headcell.setCellValue(cellList.get(i).toString());
count++;
}
}