以学生表student(id,name,age,telephone,teacher_id,remark)与教师表teacher(id,name,class_name,telephone)为例
选择要导出的行数据,ids为选择的行id。
1.controller层
/**
* 导出学生列表Excel
*/
public void studentExcel(String ids) {
//获取导出列表
List list = studentService.getAllList(ids);
//将导出列表生成excel
studentService.toExcel(response, "", list);
}
2.service层
/**
* 获取导出列
*/
List getAllList(String ids);
/**
* 导出excel
*/
void toExcel(HttpServletResponse response, String path, List list);
3.serviceImp实现层
/**
* 获取导出列
*/
@Override
public List getAllList(String ids) {
List list = studentDao.getAllList(StringUtils.stringToList(ids));
list.forEach(a -> {
});
return list;
}
/**
* 导出excel
*/
@Override
public void toExcel(HttpServletResponse response, String path, List list) {
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
String date = sd.format(new Date());
String sheetName = "学生表" + "(" + date + ")";
if (path != null && !"".equals(path)) {
sheetName = sheetName + ".xls";
} else {
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-
check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-disposition", "attachment;filename="
+ new String(sheetName.getBytes("gbk"), "ISO8859-1") + ".xls");
}
for (Student s : list) {
if (s.getAge<=20)) {
s.setRemark("20岁之下");
} else {
s.setRemark("20岁之上");
}
}
Map mapFields = new LinkedHashMap<>();
mapFields.put("name", "学生名称");
mapFields.put("age", "年龄");
mapFields.put("telephone", "联系电话");
mapFields.put("remark", "备注");
DeriveExcel.exportExcel(sheetName, list, mapFields, response, path);
} catch (Exception e) {
e.printStackTrace();
}
}
4.studentDao层
/**
* 获取导出列
**/
List getAllList(List ids);
5.xml层