1、引入poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
2、前端jsp页面
<span>
<button id="exportActivityAllBtn">导出excel</button>
</span>
js代码
$("#exportActivityAllBtn").click(function () {
window.location.href="${pageContext.request.contextPath}/exportAllActivitys" ;
});
3、controller层代码
@RequestMapping("exportAllActivitys")
public void exportAllActivitys(HttpServletResponse response) throws IOException {
//调用service的findAll()方法获取数据
//获取service层的获取所有数据方法即可
List<User> list = userService.findAll();
//用apache的poi创建excel文件,并把list写入excel文件中
//创建HSSFWorkbook对象,对应一个excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//使用wb创建HSSFSheet对象,对应wb文件中的一页
HSSFSheet sheet = wb.createSheet("user列表");//设置页名
//使用sheet创建HSSFRow对象,对应sheet中的一行
HSSFRow row = sheet.createRow(0);//索引为0就是第一行
//使用row创建HSSFCell对象,对应row中的列
HSSFCell cell = row.createCell(0);//索引为0就是第一列
//往列里设置值
cell.setCellValue("id");
cell=row.createCell(1);
cell.setCellValue("姓名");
cell=row.createCell(2);
cell.setCellValue("账号");
cell=row.createCell(3);
cell.setCellValue("性别");
cell=row.createCell(4);
cell.setCellValue("出生日期");
cell=row.createCell(5);
cell.setCellValue("所属部门");
cell=row.createCell(6);
cell.setCellValue("状态");
cell=row.createCell(7);
//遍历ActivityList,创建Row
//先判断list有没有数据
if(list!=null && list.size()>0){
User user=null;//user拿到外面定义就不用每次循环都创建,效率更高
for (int i=0;i<list.size();i++){
user=list.get(i);
//每遍历出一个user,生成一行
row=sheet.createRow(i+1);
cell = row.createCell(0);
cell.setCellValue(user.getUserId());
cell = row.createCell(1);
cell.setCellValue(user.getUserName());
cell = row.createCell(2);
cell.setCellValue(user.getAccount());
cell = row.createCell(3);
cell.setCellValue(user.isGender());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String birthDay = simpleDateFormat.format(user.getBirthDay());
cell = row.createCell(4);
cell.setCellValue(birthDay);
cell = row.createCell(5);
cell.setCellValue(user.getDept().getDeptName());
cell = row.createCell(6);
cell.setCellValue(user.getState());
}
}
//改进后!!!!!!!!!!!!!!!!!!!!!
//设置响应类型 application/octet-stream表示excel文件
response.setContentType("application/octet-stream;charset=UTF-8");
//设置响应头 Content-Disposition打开方式 attachment以附件的形式
response.addHeader("Content-Disposition","attachment;filename=userList.xls");
OutputStream out = response.getOutputStream();
wb.write(out);
wb.close();
out.flush();//out由response生成的,tomcat会自己关闭,不能自己关闭,不flush可能会数据丢失
}