我有一个GWTP应用程序,可以使用Apache POI将一些数据导出到.xlsx
文件。这是我的演示者代码。
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 :(得分:0)
您忘了关闭FileOutputStream
out
。也许尝试使用try (resource) {...}
syntax of Java7?
答案 1 :(得分:0)
尝试设置response.setContentLength((int) file.length());