直接上代码:
jsp:
说明:这里使用ajax请求是会有问题的,会导致浏览器窗口不会弹出下载提示和选择地址栏的弹窗
//导出
$('#btn-export').click(function () {
location.href = "${pageContext.request.contextPath}/exportExcel?key=key&name=name";
})
Controller:
@RequestMapping(value = "exportExcel", produces = "application/json;charset=UTF-8")
@ResponseBody
public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
HSSFWorkbook wb;
//声明文本格式
wb= exportExcelService.export();
//调用Service层的方法
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String string=sdf.format(date);
//以上内容只是为了当文件下载时,能够有一串按系统当前时间生成的数字作为命名
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename="+string+".xls");
//.xsl是文件下载的格式,该一整句就是一个声明,发送给web端的
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
Service:
public HSSFWorkbook export() {
HSSFWorkbook wb = new HSSFWorkbook(); //关键语句
Sheet sheet = null; //工作表对象
Row nRow = null; //行对象
List<xxxxView> list = xxxxViewXmlDao.findxxxxList(new xxxxView());
//因为我用的是数据库查询数据,然后返回一个list对象
int rowNo = 0; //总行号
int pageRowNo = 0; //页行号
for (int i = 0; i < list.size(); i++) {
if(rowNo%60000==0){
System.out.println("Current Sheet:" + rowNo/60000);
sheet = wb.createSheet("sheet"+(rowNo/60000));//建立新的sheet对象
sheet = wb.getSheetAt(rowNo/60000); //动态指定当前的工作表
pageRowNo = 0; //每当新建了工作表就将当前工作表的行号重置为0
}
rowNo++;
nRow = sheet.createRow(pageRowNo++); //新建行对象
if (rowNo%60000==1 || i == 0){ //该作用是再每张sheet的表格第一行写下中文栏
nRow.createCell(0).setCellValue("ID");
nRow.createCell(1).setCellValue("编号");
nRow.createCell(2).setCellValue("名称");
nRow.createCell(3).setCellValue("英文名称");
nRow.createCell(4).setCellValue("助记码");
nRow.createCell(5).setCellValue("状态");
nRow.createCell(6).setCellValue("变更时间");
nRow = sheet.createRow(pageRowNo++);
}
xxxxView View = list.get(i); //将数据库中反出的数据转换为对象
nRow.createCell(0).setCellValue(View.getid());
nRow.createCell(1).setCellValue(View.getbh());
nRow.createCell(2).setCellValue(View.getmc());
nRow.createCell(3).setCellValue(View.getywmc());
nRow.createCell(4).setCellValue(View.getZjm());
nRow.createCell(5).setCellValue(View.getState());
nRow.createCell(6).setCellValue(View.getDate());
//以上是将对象插入到每行中的每一个文本框中
}
return wb;
}
这里需要注意,上面之所以满60000数据就新建一张sheet,是因为xls文件有个单页sheet有个行数上限,最多65536行,如果不换页,导出数据是会报异常的