コード例 #1
0
ファイル: VehicleCheckAction.java プロジェクト: koalhou/J2EE
  /** 导出 */
  public String exportList(String title, String sheetName, List<AlarmEntity> exportList) {
    String filePath = "";
    OutputStream outputStream = null;
    try {

      filePath = "/tmp/" + UUIDGenerator.getUUID() + sheetName + ".xls";

      File file = new File(filePath);
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      outputStream = new FileOutputStream(filePath);
      // 使用Excel导出器IEExcelExporter
      IEExcelExporter excelExporter = new IEExcelExporter(outputStream);
      excelExporter.setTitle(
          title + "(" + searchVO.getBeginTime() + "~" + searchVO.getEndTime() + ")");

      excelExporter.putAutoExtendSheets(sheetName, 0, exportList);
      // 将Excel写入到指定的流中
      excelExporter.write();
    } catch (FileNotFoundException e) {
      log.error("Export error:" + e.getMessage());
      return ERROR;
    } catch (Exception e) {
      log.error("Export error:" + e.getMessage());
      return ERROR;
    } finally {
      // 关闭流
      if (null != outputStream) {
        try {
          outputStream.close();
        } catch (IOException e) {;
        }
      }
    }
    // 设置下载文件属性
    FileInputStream fileInputStream = null;
    OutputStream out = null;
    try {
      // 设置下载文件属性
      String fileName = URLEncoder.encode(title, "UTF8");
      HttpServletResponse response = ServletActionContext.getResponse();
      response.setHeader(
          "Content-disposition",
          "attachment;filename="
              + fileName
              + "-"
              + DateUtil.formatDateToString(new Date(), "yyyyMMddHHmmss")
              + ".xls");
      response.setContentType("application/msexcel; charset=\"utf-8\"");

      // 下载刚生成的文件
      fileInputStream = new FileInputStream(filePath);
      out = response.getOutputStream();
      int i = 0;
      while ((i = fileInputStream.read()) != -1) {
        out.write(i);
      }
    } catch (FileNotFoundException e) {
      log.error("Export error:" + e.getMessage());
      return ERROR;
    } catch (Exception e) {
      log.error("Export error:" + e.getMessage());
      return ERROR;
    } finally {
      // 关闭流
      if (null != fileInputStream) {
        try {
          fileInputStream.close();
        } catch (IOException e) {;
        }
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {;
        }
      }
    }
    return null;
  }