第一步 jsp
<button onclick="export();">
导出
</button>
function,传递需要打印的主键ids
function export(){
var selectid = getGridCheckedId("#grid-table","userId");
$("#ids").val(selectid);
$("#hiddenForm").submit();
}
第二步,controll层 例如对象为Student
@RequestMapping(value = "/export")
@ResponseBody
public void Excel() {
String ids = request.getParameter("ids");//得到要导出的ids
List<StudentModel> list = studentService.getAllLists(ids);
studentService.toExcel(response,"",list);
}
第三步,service层
List<StudentModel> getAllLists(String ids);
void toExcel(HttpServletResponse response, String path, List<UserModel> list);
第四步,serviceImp1层
@Override
public List<StudentModel> getAllLists(String ids) {
List<StudentModel> list = studentDAO.getAllLists(StringUtils.stringToList(ids));
list.forEach(a->{
if(!StringUtils.isEmptyString(a.getLastLogin())){
a.setLastLogin(DateUtils.longToStringParams(Long.parseLong(a.getLastLogin()),"yyyy-MM-dd HH:mm"));
}
});
return list;
}
@Override
public void toExcel(HttpServletResponse response, String path, List<UserModel> 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 (UserModel in : list) {
if (in.getStatus().equals(1L)) {
in.setStateName("学生");
} else if (in.getStatus().equals(2L)) {
in.setStateName("学委");
} else {
in.setStateName("班长");
}
}
Map<String, String> mapFields = new LinkedHashMap<String, String>();
mapFields.put("id", "学号");
mapFields.put("name", "姓名");
等等
DeriveExcel.exportExcel(sheetName, list, mapFields, response, path);
} catch (Exception e) {
e.printStackTrace();
}
}
第五步,dao层
List<UserModel> getAllLists(List<Long> ids);
第六步,xml层
<!--获取导出列-->
<select id="getAllLists" resultType="com.tbl.modules.platform.entity.system.StudentModel">
select * from tb_student
<if test="list!=null and list.size()>0">
and id in
<foreach item="ids" index="index" collection="list"
open="(" separator="," close=")">
#{ids}
</foreach>
</if>
</select>