数据的导出Excel表
1.原理
点击前端页面的按钮函数,函数里面去调用后端对应对的请求地址,这个请求地址所对应的方法再去调用业务层,业务层再去持久层拿到数据,返回给控制层,控制层将数据封装为比特数组的格式返回给前端页面,供客户去下载。
2.前端jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>主页面</title>
</head>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function loadFile(){
location.href="${pageContext.request.contextPath}/user/down.do"
}
</script>
<body>
<img src="${pageContext.request.contextPath}${url}" width="300px" height="300px"/>
<div>
<span>xx.file</span><button οnclick="loadFile()">下载</button>
</div>
</body>
</html>
3.控制层 处理数据
这里没有调用持久层数据,只是生成了一些假参数,但是道理是一样的。
@RequestMapping("indexHTML.do")
public String test(){
return "index";
}
@RequestMapping(value="down.do",produces="application/vnd.ms-excel")
@ResponseBody
/*
* @ResponseBody自动处理返回值,如果是javaBean处理为json,
* 如果是byte[],就将byte数填充到返回消息的body中
*/
public byte[] down(HttpServletResponse res,HttpSession session) throws IOException{
res.addHeader("Content-Disposition","attachment;filename="+"hello.xls");
//创建excel工作簿对象
HSSFWorkbook hwb=new HSSFWorkbook();
//在工作簿中创建工作表
HSSFSheet sheet=hwb.createSheet();
//创建行(从下标0开始)
//HSSFRow row=sheet.createRow(0);
//创建一个格子
//HSSFCell cell=row.createCell(0);
//给格子中添加数据
//User user=(User) session.getAttribute("user");
List<User> list=new ArrayList<User>();
for(int i=0;i<5;i++){
list.add(new User(i,"admin"+i,"pdd","521125"+i,null,null));
}
for(int i=0;i<list.size();i++){
HSSFRow row=sheet.createRow(i);
HSSFCell cell=row.createCell(0);
cell.setCellValue(list.get(i).getId());
HSSFCell cell1=row.createCell(1);
cell1.setCellValue(list.get(i).getUser_name());
HSSFCell cell2=row.createCell(2);
cell2.setCellValue(list.get(i).getUser_pwd());
}
//将excel对象序列化为byte[]数据
ByteArrayOutputStream baos=new ByteArrayOutputStream();
//将hwb对象写入到baos对象中
hwb.write(baos);
hwb.close();
//将baos对象转化为数组
byte[] bytes=baos.toByteArray();
return bytes;
}
4.结果分析
1.当我们输入请求 地址后
2.我们点击下载
3.点击确定,就会下载了,然后我们打开excel表,就会得到我们 想要得到的数据了