关于导入与导出,本文使用到5个jar包,导入5个jar包都需要使用,而导出的没有留意但引用完后便可以书写导出,分别是:poi-3.8-20120326.jar、poi-ooxml-3.8-20120326.jar、
poi-ooxml-schemas-3.8-20120326.jar、dom4j-1.6.1.jar、xmlbeans-2.3.0.jar。
总体思路:按条件查询出需要导出的数据,可以在分页查询时写入不分页的查询语句,查询到需要导出的数据,然后保存到Session中,在页面点击导出按钮,弹出选择导出列模态框,选择需要导出的列后,提交到servlet在servlet中读取Session中保存的数据。然后创建excel表单(sheet),在创建好的excel表单中创建首行,然后在首行中创建单元格并设置内容,内容为所需要导出列的列名,声明一个int对象用于记录行号,使用迭代器遍历数据,在迭代器中添加行,循环需要导出的列,根据列在行中添加单元格并赋值,最后设置文件名,本文使用的方法是导出表格数据的名称加上年月日再加上随机数再加后缀名。代码如下(本文不包括查询代码,对查询代码不理解的可自行上网学习):
String topCell2=request.getParameter("topCell");
String[] topCell=topCell2.split(",");
List<SelectSupplierLinkmanVo>listSupplierLinkman=(List<SelectSupplierLinkmanVo>)request.getSession().getAttribute("listSupplierLinkman");
//建立新的sheet对象(excel的表单)
HSSFSheet sheet=wb.createSheet("供应商联系人表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
int rowNum=0;
HSSFRow row1=sheet.createRow(rowNum);
for (int i = 0; i < topCell.length; i++) {
String string = topCell[i];
//创建单元格并设置单元格内容
row1.createCell(i).setCellValue(string);
}
rowNum++;
for (Iterator<SelectSupplierLinkmanVo> iterator = listSupplierLinkman.iterator(); iterator.hasNext();) {
SelectSupplierLinkmanVo selectSupplierLinkmanVo = (SelectSupplierLinkmanVo) iterator.next();
HSSFRow row=sheet.createRow(rowNum);
for (int i = 0; i < topCell.length; i++) {
String string = topCell[i];
//创建单元格并设置单元格内容
if("供应商名称".equals(string)){ row.createCell(i).setCellValue(selectSupplierLinkmanVo.getSupplierName());
}else if("联系人姓名".equals(string)){ row.createCell(i).setCellValue(selectSupplierLinkmanVo.getName());
}
rowNum++;
}
Date date=new Date();
SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyyMMdd");
String strDate=dateFormat1.format(date);
Random rand=new Random();
String fileName="供应商联系人"+strDate+rand.nextInt(100)+".xls";
OutputStream output=response.getOutputStream();
//清除任何缓存中的任何数据,包括状态码和各种响应头
response.reset();
//使用指定名称和值设置响应头的名称和内容
response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
//设置响应的内容的类型,如果响应还未被提交的话
response.setContentType("application/msexcel");
wb.write(output);
output.close();
注意在页面中javaScript执行的方法是(url指向方法名):window.location.href="url?topCell="+topCell;
效果图如下: