标签:ssh
poi目前应该是比较流行的操作excel的工具了,这几天做了个struts2和poi结合使用来实现导出excel的功能,个人觉得还是比较实用的,代码阅读起来也很简单,下来就来分享下我的心得
1 struts2的下载excel文件机制
struts2的action中使用poi和输入输出流把二进制数据通过流的形式响应给客户端,客户端浏览器作出响应的处理,如弹出文件下载对话框
2 poi的使用方法
poi解析或生成excel网上资料特别多,这里我就不给出代码了
3 struts文件的相关配置
<result name="export" type="stream"> <param name="contentType">application/xls;charset=UTF-8</param> <param name="contentDisposition">attachment;filename="${downloadFileName}"</param> <param name="inputName">excelFile</param> </result>
4 action的主要内容
(1)相关属性的getter和setter方法
private InputStream excelFile; private String downloadFileName=String.valueOf(Calendar.getInstance().getTimeInMillis())+".xls"; public InputStream getExcelFile() { return excelFile; } public void setExcelFile(InputStream excelFile) { this.excelFile = excelFile; } public String getDownloadFileName() { return downloadFileName; } public void setDownloadFileName(String downloadFileName) { this.downloadFileName = downloadFileName; }
public void ExcelFile(String startCardNum,String num) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); HSSFRow row = sheet.createRow(0); //单元格和工作薄名称都要设置下编码,否则有中文的时候就会出现乱码 workbook.setSheetName(0, "卡号信息表" , HSSFWorkbook.ENCODING_UTF_16); HSSFCell cell1=row.createCell((short)0); cell1.setEncoding(HSSFWorkbook.ENCODING_UTF_16); cell1.setCellValue("卡号"); HSSFCell cell2=row.createCell((short)1); cell2.setEncoding(HSSFWorkbook.ENCODING_UTF_16); cell2.setCellValue("密码"); HSSFCell cell3=row.createCell((short)2); cell3.setEncoding(HSSFWorkbook.ENCODING_UTF_16); cell3.setCellValue("创建时间"); //取得符合条件的卡号信息 List<Card> all=cardService.queryCardByCondition(startCardNum, num); Iterator<Card> it=all.iterator(); int j=1; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); while(it.hasNext()){ row=sheet.createRow(j); Card c=it.next(); row.createCell((short)0).setCellValue(c.getCardNum()); row.createCell((short)1).setCellValue(c.getPassword()); row.createCell((short)2).setCellValue(sdf.format(c.getCreateDate())); j++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { workbook.write(baos); } catch (IOException e) { e.printStackTrace(); } byte[] aa = baos.toByteArray(); excelFile = new ByteArrayInputStream(aa,0,aa.length); try { baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
(3)导出excel的总方法
public String exportCardInfo() throws Exception { String startNum=this.getRequest().getParameter("startCardNum"); String num=this.getRequest().getParameter("num"); ExcelFile(startNum,num); this.setDownloadFileName(String.valueOf(Calendar.getInstance().getTimeInMillis())+".xls"); return "export"; }
标签:ssh
原文地址:http://blog.csdn.net/smartcodekm/article/details/37990971