前端发送请求,不可以用ajax
如果采用ajax,则下载默认会读取response返回的二进制数据,前端不会有执行下载动作,并且reponse的内容是乱码的
需要用表单提交的方式
后台代码:ssm框架
@RequestMapping("/importLessonByClazz")
public void importLessonByClazz(String className,String beginweeks,String endweeks,HttpServletResponse response){
//查询数据
Clazz clazz = clazzService.getClazzById(Integer.parseInt(className));
ImprotLesson il = new ImprotLesson();
il.setId(Integer.parseInt(clazz.getClassroomid()));
il.setBegion(beginweeks);
il.setEnd(endweeks);
java.util.List<Lesson> list = lessonService.searchLessonByClassroomId(il);
java.util.List<Tree> list2 = lessonTypeService.getLessonTypeTree(new LessonType());
// excel的文档对象
HSSFWorkbook book = new HSSFWorkbook();
// excel的表单
HSSFSheet sheet = book.createSheet();
int i=0;
if(list.size()>0){
//excel的行
HSSFRow row = sheet.createRow(i++);
//利用excel的行对象创建单元格对象并赋值,单元格从0开始
row.createCell(0,3).setCellValue("班级课程表");
for (int j = Integer.parseInt(beginweeks); j < Integer.parseInt(endweeks)+1; j++) {//周
HSSFRow row1 = sheet.createRow(i++);
row1.createCell(0).setCellValue("");
row1.createCell(1).setCellValue("第一节课");
row1.createCell(2).setCellValue("第二节课");
row1.createCell(3).setCellValue("第三节课");
row1.createCell(4).setCellValue("第四节课");
row1.createCell(5).setCellValue("第五节课");
row1.createCell(6).setCellValue("第六节课");
row1.createCell(7).setCellValue("第七节课");
row1.createCell(8).setCellValue("第八节课");
for (int j2 = 0; j2 < 7; j2++) {//天
HSSFRow row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue("周"+(j2+1));
for (int k = 0; k < 8; k++) {//课
for (Lesson lesson : list) {
if(Integer.parseInt(lesson.getWeeks())==j&&Integer.parseInt(lesson.getWeekday())==(j2+1)&&Integer.parseInt(lesson.getTime())==(k+1)){
for (Tree tree : list2) {
if(lesson.getName().equals(tree.getId())){
row2.createCell(k+1).setCellValue(tree.getText());
}
}
break;
}
}
}
}
}
}
try {
response.setContentType("application/vnd.ms-excel");
//文件名
String string = new String("班级课程表.xls".getBytes("utf-8"),"ISO8859-1");
//设置文件在浏览器下载
response.setHeader("Content-Disposition", "attachment;filename="+string);
ServletOutputStream out = response.getOutputStream();
book.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}