2014-10-28 64 views
0

我想添加一个函数到我的web应用程序,它可以让用户下载一个excel文件。Java HttpServlet如何下载excel文件

我想用下面的代码来实现这一目标:

@Override 
    public void doPost(HttpServletRequest request, HttpServletResponse response) { 
     File file = new File("d:/test/test.xls"); 
     response.setContentType("application/xls"); 
     response.addHeader("Content-Disposition", "attachment; filename=test.xls"); 
     response.setContentLength((int) file.length()); 

     try { 
      FileInputStream fileInputStream = new FileInputStream(file); 
      OutputStream responseOutputStream = response.getOutputStream(); 
      int bytes; 
      while ((bytes = fileInputStream.read()) != -1) { 
       responseOutputStream.write(bytes); 
      } 
      fileInputStream.close(); 
      responseOutputStream.close(); 

     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

我能下载Excel与上面的代码文件,但该文件已损坏。如果我用microsoft excel打开它,我会弹出消息:

“文件格式和扩展名不匹配,文件可能已损坏或不安全”。

而excel文件是空的。

运行代码后,原始文件(d:/test/test.xls)也被破坏。

我在做什么错?

+0

确定的Excel文件attemting下载它之前是否有效?它可能是它的过程之前已经损坏了吗? – icza 2014-10-28 14:58:11

+0

是的,我很确定。 – MeesterPatat 2014-10-28 14:58:28

+0

那么,有一件事是肯定的,您发布的代码肯定不会修改或损坏您的Excel文件。 – icza 2014-10-28 15:00:05

回答

1

Excel文件.xls的官方MIME类型是application/vnd.ms-excel,而.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet

此外,我建议在写入输出流之前先做response.reset(),然后在关闭response之前写入responseOutputStream.flush()(重要)。

0

试试下面的代码:

File file = null; 
    InputStream in = null; 
    OutputStream outstream = null; 
    try { 
     response.reset(); 
     in = new FileInputStream(file); 
     response.setContentType("application/vnd.ms-excel"); 
     response.addHeader("content-disposition", "attachment; filename=data.xls"); 
     outstream = response.getOutputStream(); 
     IOUtils.copyLarge(in, outstream); 
    } 
    catch (Exception e) { 
     out.write("Unable to download file"); 
    }finally { 
     IOUtils.closeQuietly(outstream); 
     IOUtils.closeQuietly(in); 
     IOUtils.closeQuietly(out); 
     if (file != null) 
      file.delete(); 
    } 

不要忘了补充阿帕奇公地IO-2.4在你的依赖