Struts的POI导出Excel文件

原理:先写在内存中,然后读出来打开或下载

在****Action里有如下方法:

 public InputStream getDownloadFile(){
  return this.*Service.getInputStream();
 }
 
 public String getInputStream(){
  return SUCCESS;
 }

 

 

在***Service.java里有getInputStream方法,具体代码如下:

 public InputStream getInputStream() {
  HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
  HSSFSheet hssfSheet = hssfWorkbook.createSheet("sheet1");

  HSSFRow hssfRow = hssfSheet.createRow(0);

  HSSFCell hssfCell = hssfRow.createCell((short) 0);

  hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
  hssfCell.setCellValue("列名一");

  hssfCell = hssfRow.createCell((short) 1);
  hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
  hssfCell.setCellValue("列名二");

  …………

  //这里获取导出的数据,可根据情况变化
  List<tableName> tableNameList = this.tableNameDao.findAll();
  
  for (int i = 0; i < tableNameList.size(); i++) {
   TableName tableName = tableNameList.get(i);
   hssfRow = hssfSheet.createRow(i+1);

   hssfCell = hssfRow.createCell((short) 0);
   hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   hssfCell.setCellValue(tableName.get***());// 列一填充数据

   hssfCell = hssfRow.createCell((short) 1);
   hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   hssfCell.setCellValue(tableName.get***());

……………………

  }
  //创建文件用10个长度的随机名
  File tableNameFile = new File(new StringBuffer(RandomStringUtils.randomAlphanumeric(10)).append(".xls").toString());
  // 创建输出流
  try {
   OutputStream outputStream = new FileOutputStream(tableNameFile);
   hssfWorkbook.write(outputStream);
   outputStream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  // 创建输入流
  InputStream inputStream = null;;
  try {
   inputStream = new FileInputStream(tableNameFile);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  return inputStream;
 }

 

struts.xml里面配置

<action name="l" method="getInputStream" class="***Action">
   <result name="success" type="stream">
    <param name="contentType">application/vnd.ms-excel</param>
    <param name="contentDisposition">attachment;filename="必须英文名字.xls"</param>
    <param name="inputName">downloadFile</param>
    <param name="bufferSize">1024</param>
   </result>
  </action>

你可能感兴趣的:(struts,String,Excel,File,Class,action)