java项目中把数据导出到excel文件中

private void exportScore(HttpServletRequest request, HttpServletResponse response) {
int studentId = request.getParameter(“studentid”) == null ? 0 : Integer.parseInt(request.getParameter(“studentid”).toString());
int courseId = request.getParameter(“courseid”) == null ? 0 : Integer.parseInt(request.getParameter(“courseid”).toString());
//获取当前登录用户类型
int userType = Integer.parseInt(request.getSession().getAttribute(“userType”).toString());
if(userType == 2){
//如果是学生,只能查看自己的信息
Student currentUser = (Student)request.getSession().getAttribute(“user”);
studentId = currentUser.getId();
}
Score score = new Score();
score.setStudentId(studentId);
score.setCourseId(courseId);
try {
//响应头必须设置,固定写法
response.setHeader(“Content-Disposition”, “attachment;filename=”+URLEncoder.encode(“score_list_sid_”+studentId+“cid”+courseId+".xls", “UTF-8”));
response.setHeader(“Connection”, “close”);
response.setHeader(“Content-Type”, “application/octet-stream”);
//设置输出流
ServletOutputStream outputStream = response.getOutputStream();
ScoreDao scoreDao=new ScoreDao();
//通过学生id和课程id获取所有的信息
List<Map<String, Object>> scoreList = scoreDao.getScoreList(score);
//关闭流
scoreDao.closeCon();
//通过HSSFWorkbook类创建表
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet createSheet = hssfWorkbook.createSheet(“学生列表”);
//创建表之后开始创建第0行
HSSFRow createRow = createSheet.createRow(0);
//创建行之后开始创建列,并且未列名设置值
createRow.createCell(0).setCellValue(“学生”);
createRow.createCell(1).setCellValue(“课程”);
createRow.createCell(2).setCellValue(“成绩”);
createRow.createCell(3).setCellValue(“备注”);
//上面是创建第0行,应该更具查询到的scoreList来决定创建多少行多少列
int row=0;
for (Map<String, Object> entry : scoreList) {
createRow= createSheet.createRow(row++);
createRow.createCell(0).setCellValue(entry.get(“studentName”).toString());
createRow.createCell(1).setCellValue(entry.get(“courseName”).toString());
createRow.createCell(2).setCellValue(new Double(entry.get(“score”)+""));
createRow.createCell(3).setCellValue(entry.get(“remark”)+"");
}
//HSSFWorkbook创建的表的信息写道流里面去,然后关闭创建的流
hssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

发布了19 篇原创文章 · 获赞 0 · 访问量 390

猜你喜欢

转载自blog.csdn.net/weixin_45014243/article/details/104421117