写电子表内容:

public byte[] writeMapData(Map<String,List<Map<String,Object>>> data) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
WritableWorkbook wwb = Workbook.createWorkbook(os);
int sheetIndex=0;
for (Map.Entry<String, List<Map<String, Object>>> s :
data.entrySet()) {
WritableSheet writableSheet = wwb.createSheet(s.getKey(),sheetIndex);
List<Map<String,Object>> sheetData = s.getValue();
if(sheetData.size()==0){
continue;
}

//region 取列
List<String> colList = new ArrayList<>();
Map<String, Object> mapCol = sheetData.get(0);
Iterator iterator = mapCol.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
colList.add(entry.getKey().toString());
}
//endregion

//region 写数据
int rowIndex = 0;
int colIndex = 0;

for (String str :
colList) {
WritableFont wf = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD, false);
WritableCellFormat wcf = new WritableCellFormat(wf);
Label label = new Label(colIndex, rowIndex, str, wcf);
writableSheet.addCell(label);
colIndex++;
}

rowIndex++;

for (Map<String, Object> obj :
sheetData) {
colIndex = 0;
for (String str :
colList) {
String value = "";
if (obj.get(str) != null) {
value = obj.get(str).toString();
}
Label label = new Label(colIndex, rowIndex, value);
writableSheet.addCell(label);
colIndex++;
}
rowIndex++;
}
//endregion

sheetIndex++;
}
wwb.write();
wwb.close();
return os.toByteArray();
}

控制器方法向浏览器返回文件:

 @RequestMapping("/downloadTeacherMb")
@LoginLimit(limit = false)
public void downloadTeacherMb(HttpServletResponse response) throws Exception {
List list1 = codeMapper.listAll(1);
List list2 = codeMapper.listAll(2);
List list3 = codeMapper.listAll(3);
List<Map<String, Object>> listT = new ArrayList<>();
Map<String, Object> mapT = new LinkedHashMap<>();
mapT.put("姓名", "");
mapT.put("barcode", "");
mapT.put("性别", "");
mapT.put("身份证号码", "");
mapT.put("联系电话", "");
mapT.put("民族代码", "");
mapT.put("政治面貌代码", "");
mapT.put("学历代码", "");
mapT.put("毕业学校", "");
mapT.put("出生年月", "");
mapT.put("联系地址", "");
listT.add(mapT);

Map<String, List<Map<String, Object>>> map = new LinkedHashMap<>();
map.put("教师数据表", listT);
map.put("学历代码对照表", list1);
map.put("民族代码对照表", list2);
map.put("政治面貌代码对照表", list3);

Excel excel = new Excel();
byte[] data = excel.writeMapData(map);

response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("教师导入模版", "UTF-8") + ".xls");

OutputStream stream = response.getOutputStream();
stream.write(data);
stream.flush();
stream.close();
}

说明:
1、控制器方法使用HttpServletResponse 参数
2、LinkedHashMap是有序的,可以确保列的顺序
3、setContentType设置返回类型
4、header中Content-Disposition 设置返回文件名,URLEncoder.encode给文件名编码
5、这个写电子表的方法写的只支持xls格式,不支持xlsx格式