导出csv文件

时间:2014-05-29 05:59:10

标签: java csv

我正在尝试导出 csv 文件。调试时,我能够在控制台中看到所有数据,但文件创建存在一些问题。请帮帮我。 SomeBean 是我的托管bean。

    public void export() {

    final StringBuffer sb = new StringBuffer();
      for( SomeBean data : lstSomeData) {

        sb.append(data.getId());
        sb.append(',');
        sb.append(data.getDesc());
        sb.append(',');
        sb.append(data.getSomeId());
        sb.append('\n');
      }

      String userName = WebConstants.EMPTY_STRING;

      Prin prin = FacesContext.getCurrentInstance().getExternalContext().getUserPrin();
      userName = prin.getName();
      StringBuilder fileNameBuilder = new StringBuilder();
      fileNameBuilder.append("attached;").append("filename=\"");
      fileNameBuilder.append("SOME").append("_").append(userName)
      .append("_")..append(".csv");//.append("\"");

      byte[] csvData = null;
      // in case you need some specific charset :
      // here is an example with some standard utf-8

      try{
          csvData = sb.toString().getBytes("utf-8");
      }catch(UnsupportedEncodingException ue) {
         logger.error(" UnsupportedEncodingException in SomeMB :"+ue);
      }

      final FacesContext context = FacesContext.getCurrentInstance();
      final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
      response.setHeader("Content-disposition",fileNameBuilder.toString());
      response.setContentType("application/vnd.ms-excel");

      try {
          response.getOutputStream().write(csvData);
          response.getOutputStream().flush();
          response.getOutputStream().close();
          context.responseComplete();
          //Telling the framework that the response has been completed.
          FacesContext.getCurrentInstance().responseComplete();
      } catch (final IOException e) {
         logger.error(" Exception while export :"+e);
      }
}

0 个答案:

没有答案