上一篇博客我们分享了数据上传经验《导入Excel》。今天我们来分享一下数据下载经验:导出Excel!
1、添加ExcelUtility工具类(完整版链接)
2、实现导出Excel
1、添加ExcelUtility工具类
(1)ExcelUtility工具类中导出Excel代码:
/**
* @MethodName : listToExcel
* @Description : 导出Excel
* @param response:使用response可以导出到浏览器
* @param list:数据源
* @param fieldMap:中英文字段对应Map
* @throws ExcelException
*/
public void listToExcel (
HttpServletResponse response,
List list ,
LinkedHashMap fieldMap) throws ExcelException{
//设置默认文件名为当前时间:年月日时分秒
String fileName=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
//设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); //改成输出excel文件
response.setHeader("Content-disposition","attachment; filename="+fileName+".xls" );
//创建工作簿并发送到浏览器
try {
OutputStream out=response.getOutputStream();
listToExcel(out, list, fieldMap);
} catch (Exception e) {
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(e instanceof ExcelException){
throw (ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
}else{
throw new ExcelException("导出Excel失败");
}
}
}
(2)在web的pom文件里添加相关依赖:
com.tgb
itoo-assess-tool
0.0.1-SNAPSHOT
2、实现导出Excel
(1)前台Jsp代码
建议Id
教师Id
课程Id
学生建议
(
2)前台js代码
// 导出Excel方法
function printSuggestion(){
var teacherId=teaId.innerHTML;
var courseId=courId.innerHTML;
alert("执行到这里");
//调用导出Excel方法
$.ajax({
type : 'post',
url : "exportExcel?teacherId=" + teacherId+"&courseId="+courseId,
// dataType : "text",
})
}
(3)后台Controller代码
/**
* 导出excel
* @param request 请求
* @param resposne 响应
* @throws UnsupportedEncodingException 编码异常
*/
@RequestMapping("/exportExcel")
public void leadToExcelQuestionBank(HttpServletRequest request, HttpServletResponse response)
throws UnsupportedEncodingException {
// String courseId = request.getParameter("courseId").trim();
// String teacherId = request.getParameter("teacherId").trim();
String courseId = request.getParameter("courseId");
String teacherId = request.getParameter("teacherId");
courseId = "jisuanjiyingyong123";
teacherId = "wangyajin001";
//Excel要导出的数据
List suggestions=studentAssessSuggestionBean.findSuggestionByIdExcel(teacherId,courseId);
LinkedHashMap fieldMap=new LinkedHashMap();
fieldMap.put("teacherName","教师姓名");
fieldMap.put("courseName","课程名称");
fieldMap.put("suggestion","学生建议");
try {
excelUtil=new CommonExcelUtil();
excelUtil.listToExcel(response, suggestions, fieldMap);
} catch (Exception e) {
e.printStackTrace();
}
}
(4)StudentAssessSuggestionBeanImpl代码:
@SuppressWarnings("unchecked")
public List findSuggestionByIdExcel(String teacherId, String courseId) {
//查询语句的参数map
Map map=new HashMap();
map.put("teacherId", teacherId);
map.put("courseId", courseId);
String hql=null;
hql="From StudentAssessSuggestion where teacherId=:teacherId and courseId=:courseId ";
List studentAssessSuggestion = studentAssessSuggestionEao.queryByHql(hql, map);
return studentAssessSuggestion;
}
ok,到这里为止数据下载经验--导出Excel已经完成。
总结
从用户角度出发,以用户为主,越靠近用户的使用习惯,软件亲和力越高,开发的软件越受欢迎!