1、前台写一个按钮跳到控制层
<a href="account.do?flag=out" >导出表格</a>
2、控制层导出数据方法
@RequestMapping(value = "account.do",params = "flag=out")
//String视图解析器
public void out(HttpServletResponse response,HttpSession session,HttpServletRequest request)
throws ServletException, IOException{
// 获取相对路径
String filepath = request.getServletContext().getRealPath("/")+"\include\template\scoreInfo.xls";
File file = new File(filepath);
FileInputStream fileIn = new FileInputStream(file);
HSSFWorkbook workBook = new HSSFWorkbook(fileIn);
HSSFRow row = null;
HSSFCell cell = null;
// 第一个sheet页
HSSFSheet sheet = workBook.getSheetAt(0);
// 起始行
int startRow = 4;
row = sheet.getRow(2);
//填写制作人 第2个格
cell = row.getCell((short) 1);
session = request.getSession();
if(session.getAttribute("realName")!=null) {
cell.setCellValue((String)session.getAttribute("realName"));
}else {
cell.setCellValue("");
}
// 填写日期
HSSFRow row2 = null;
HSSFCell cell2 = null;
row2 = sheet.getRow(2);
// 第6个格
cell2 = row2.getCell((short) 5);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
cell2.setCellValue(date);
// excel表格需要写入的信息
List<Account> list = accountMapper.sellectAll();
for (int i = 0; i < list.size(); i++) {
row = sheet.getRow(startRow+i);
// NO从1开始
cell = row.getCell((short) 0);
cell.setCellValue(i+1);
// 账号名 Accname
cell = row.getCell((short) 1);
cell.setCellValue(list.get(i).getAccname());
// 姓名 Accrealname
cell = row.getCell((short) 2);
cell.setCellValue(list.get(i).getAccrealname());
// 电话 Accphone
cell = row.getCell((short) 3);
cell.setCellValue(list.get(i).getAccphone());
// 生日Accbirthday
cell = row.getCell((short) 4);
cell.setCellValue(list.get(i).getAccbirthday());
// 角色
cell = row.getCell((short) 5);
cell.setCellValue(list.get(i).getRole().getRolename());
// 状态
cell = row.getCell((short) 6);
cell.setCellValue(list.get(i).getStatus().getStatusname());
}
OutputStream out = response.getOutputStream();
response.resetBuffer();
response.addHeader("Pragma", "no-cache");
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode("scoreInfo", "UTF-8") + ".xls");
try {
workBook.write(out);
} finally {
fileIn.close();
out.close();
response.flushBuffer();
workBook.close();
}
}
3、数据需要导入的Excel表格模板
注意日期:右键设置单元格格式 日期格式
4、先运行一下程序会报找不到文件路径异常
按照报错的地址建立文件夹以及把表格放入