前面两篇文章已经介绍了POI导出表格的基本使用、常见excel的导出。
使用HSSFWorkbook导出、操作excel
使用HSSFWorkbook导出一份Excel版个人信息表
这一篇文章是介绍导出一个excel创建多个sheet工作表的示例。有时候我们需要对数据归纳分类处理,因此会需要多个工作表展示,让数据更加清晰、一目了然。
下面是效果图:

一:导出表格方法
/**
* 导出学校信息,有多个工作表sheet
* @param request
* @param response
*/
public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
try {
String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
response.setContentType("application/msexcel");
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("UTF-8"), "8859_1") + ".xls");
HSSFWorkbook workbook = new HSSFWorkbook();
OutputStream os = response.getOutputStream();
Map<String,List<School>>resultMap = School.getJsonMap();
if(null == resultMap){
workbook.write(os);
os.close();
return;
}
createExcelSheet(workbook,"文科",resultMap);
createExcelSheet(workbook,"理科",resultMap);
os = response.getOutputStream();
workbook.write(os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二:生成单个工作表方法
/**
* 生成单个工作表
* @param workbook
* @param sheetName
* @param dataMap
*/
public static void createExcelSheet(HSSFWorkbook workbook , String sheetName, Map<String,List<School>> dataMap){
try {
HSSFSheet sheet = workbook.createSheet(sheetName);
int columnSize = 6;
//设置列宽
for(int i = 0;i< columnSize;i++ ){
sheet.setColumnWidth(i, 4000);
}
sheet.setColumnWidth(2, 10000);
sheet.setColumnWidth(4, 15000);
// 设置字体
HSSFFont headfont = workbook.createFont();
headfont.setFontName("宋体");
// 字体大小
headfont.setFontHeightInPoints((short) 22);
// 加粗
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//头部样式
HSSFCellStyle headstyle = workbook.createCellStyle();
headstyle.setFont(headfont);
// 左右居中
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 上下居中
headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
headstyle.setLocked(true);
// 自动换行
headstyle.setWrapText(true);
headstyle.setBorderLeft((short) 1);
headstyle.setLeftBorderColor(HSSFColor.BLACK.index);
headstyle.setRightBorderColor(HSSFColor.BLACK.index);
headstyle.setBottomBorderColor(HSSFColor.BLACK.index);
headstyle.setBorderBottom((short) 1);
headstyle.setBorderRight((short) 1);
// 加粗字体样式
HSSFFont columnHeadFont = workbook.createFont();
columnHeadFont.setFontName("宋体");
columnHeadFont.setFontHeightInPoints((short) 12);
columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 列头的样式
HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
columnHeadStyle.setFont(columnHeadFont);
columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
columnHeadStyle.setLocked(true);
columnHeadStyle.setWrapText(true);
columnHeadStyle.setTopBorderColor(HSSFColor.BLACK.index);
columnHeadStyle.setBorderTop((short) 1);
columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);
columnHeadStyle.setBorderLeft((short) 1);
columnHeadStyle.