cjmiou 发表于 2013-1-28 18:58:54

用Apache POI导出Excel

Service中的代码如下:
public InputStream getInputStream() {HSSFWorkbook wk = new HSSFWorkbook();HSSFSheet sheet = wk.createSheet("UserList");HSSFRow row = sheet.createRow(0);HSSFCell cell = row.createCell((short)0);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("序号");cell = row.createCell((short)1);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("姓");cell = row.createCell((short)2);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("名");cell = row.createCell((short)3);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("年龄");List<User> userList = this.getUserList();for(int i=0;i<userList.size();++i){User user = userList.get(i);row = sheet.createRow(i+1);cell = row.createCell((short)0);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getId());cell = row.createCell((short)1);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getFirstname());cell = row.createCell((short)2);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getLastname());cell = row.createCell((short)3);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getAge());}//此处对文件进行了命名,但是下载时的文件默认名字实际上是struts.xml中配置的名字,//此文件是在tomcat服务器中bin目录中的临时文件的名字File file = new File("test.xls");try {OutputStream os = new FileOutputStream(file);wk.write(os);os.close();} catch (IOException e) {e.printStackTrace();}InputStream is=null;try {is = new FileInputStream(file);} catch (FileNotFoundException e) {e.printStackTrace();}return is;} 
action中所要使用到的方法如下:
      public InputStream getDownloadFile(){return this.userService.getInputStream();}public String generateExcel(){return SUCCESS;} 其中的实例的action只返回了一个success

struts.xml应做如下配置:
<action name="generateExcel" class="userAction" method="generateExcel"><!-- 指定type为stream类型 --><result name="success" type="stream"><!-- 指定输出的为Excel文件 --><param name="contentType">application/vnd.ms-excel</param><!-- 指定下载时文件的默认名字,注貌似不能使用中文,同时filename不能写成fileName --><param name="contentDisposition">filename="AllUser.xls"</param>                              <!-- 此处的值是对应于action中的某个返回值为InputStream的方法,如为下面的配置,那么 userAction中需要有一个public InputStream getDownloadFile()的方法 -->                                 <param name="inputName">downloadFile</param></result></action> 
type应为stream,所有param元素中的name属性的值大小写要区别,如inputName不能写成inputname,
 
 
这里的程序还有一个问题,也就是那个临时文件的问题,即当某一个用户点击生成Excel链接后,执行生成"text.xls"后,正准备往外面输出文件,就在这时,另一用户又点击了同一个链接,这就导致了一个严重的问题,也就是当某一用户正要往外输出流的时候,另一个用户正准备创建这个流或者正要写这个流!解决这个问题有两个方法,见下一篇博文。

 
页: [1]
查看完整版本: 用Apache POI导出Excel