2016-01-18 26 views
0

我有一個GWTP應用程序可以使用Apache POI將一些數據導出到.xlsx文件。這是我的主持人代碼。Spring + GWTP:從OutputStream下載Excel文件不起作用

protected void exportTable(String selectedPublisher, String selectedTarget, Drilldown drilldown) { 
    this.excelServiceAsync.generateDataEnrichmentExport(selectedPublisher, new AsyncCallback<Void>() { 
     @Override 
     public void onSuccess(Void result) { 
      Window.open(GWT.getModuleBaseURL() + "rpc/excelDownload", "_blank", "");  
     } 

     @Override 
     public void onFailure(Throwable caught) { 
      Window.alert("Error!"); 
     } 
    }); 

} 

這是我的excel代碼,由演示者異步調用。

workbook = new XSSFWorkbook(); 
sheetOne = workbook.createSheet("Export One"); 

// TODO Typical POI coding stuff 

FileOutputStream out = null; 

try { 
    out = new FileOutputStream(new File("file.xlsx")); 
    workbook.write(out);  
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

這裏是我用來下載excel文件的控制器。

@ResponseBody 
@RequestMapping(value = "/excelDownload") 
public String downloadExcel(HttpServletRequest request, HttpServletResponse response){ 

    File file = new File("file.xlsx"); 

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
    response.setHeader("Content-Disposition", "attachment; filename=" 
      + "file.xlsx"); 
    response.setHeader("Content-Length", String.valueOf(file.length())); 

    FileInputStream is = null; 

    try { 
     is = new FileInputStream(file); 
     IOUtils.copy(is, response.getOutputStream()); 

     response.flushBuffer(); 
     response.getOutputStream().close(); 
    } catch (FileNotFoundException e) { 
     logger.error(e.getMessage(), e.getCause()); 
    } catch (IOException e) { 
     logger.error(e.getMessage(), e.getCause()); 
    } finally { 
     try { 
      is.close(); 
     } catch (Exception ex) { 
      return "redirect:/error/internal"; 
     } 
    } 

    return ""; 
} 

我正在生成excel文件並放在輸出流。然後在控制器中,我從輸出流中獲取數據作爲.xlsx文件下載。這不起作用。工作文件被生成並保存在服務器上。但瀏覽器下載的文件是損壞的文件。我不確定爲什麼。請幫忙!

回答

0

您忘記關閉您的FileOutputStreamout。也許嘗試使用try (resource) {...} syntax of Java7

+0

我關閉'FileOutputStream'在控制器上爲'response.getOutputStream()關閉();'所以這是沒有問題的。我也嘗試在演示者中使用'out.close()'。無論哪種方式,它都不能解決問題。 –

+0

按照我的建議,使用更新的代碼編輯您的文章,最好使用try-with-resource語法,這樣我們都可以看到如何關閉流。 –

0

儘量設置response.setContentLength((int) file.length());