GWT下载Excel .xlsx给我一个损坏的文件

在我工作的团队中,我正在开发一个GWT应用程序,它使公司中的每个团队都了解他们必须做的事情。 该程序正在工作,但现在我们希望您可以下载的Excel表格将是一个* .xlsx而不是一个xls这个整个项目对我来说是新的,我认为自己作为GWT的初学者。

在代码中为Exceltable提供文件名时,最后有一个+“。xls”。 但是,当我改变它+“。xlsx”和testing应用程序的下载仍然工作,但是当我尝试在Excel中打开该文件时,它显示了一个错误消息,并告诉我该文件已损坏? (.xls作品)

你能解释一下如何使用一个serverSite生成的Excel在GWT下载工作? 也许你有一些想法是什么导致文件被损坏(可惜这个应用程序的程序员在假期,所以我不能问他…)

提前致谢

编辑:

public class Download extends HttpServlet { private static final long serialVersionUID = 5580666921970339383L; @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = (String)request.getSession().getAttribute(CrossReportConstants.ATTR_FILENAME); byte[] data = (byte[])request.getSession().getAttribute(CrossReportConstants.ATTR_REPORT); request.getSession().setAttribute(CrossReportConstants.ATTR_FILENAME, null); request.getSession().setAttribute(CrossReportConstants.ATTR_REPORT, null); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + filename); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setContentLength(data.length); try { InputStream in = new ByteArrayInputStream(data); ServletOutputStream out = response.getOutputStream(); byte[] outputByte = new byte[4096]; // copy binary contect to output stream while (in.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } in.close(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } } 

现在,当您提供代码时,您可以轻松回答问题:

显示的代码定义了一个HttpServlet 。 在你的项目的某个地方有一个名为web.xml的文件。 在这个文件中,你显示的类被映射到一个url模式,因此你的服务器知道一个特定的url应该被这个servlet处理。

您首先显示的servlet会将会话中的文件名和文件内容提取出来。 另外准备http响应并写出文件内容。 现在,您只需将响应的内容typesreplace为xlsx的内容types即可。

 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 

处理http响应的浏览器现在将下载识别为.xlsx文件。 正如你注意到的那样,文件扩展名在这一步中并不重要。

当servlet的原程序员从他的hollidays回来时,你应该/可以推荐他使用response.sendError() (带有适当的http状态码)而不是e.printStackTrace() 。 然后,servlet的用户可以更好地理解是否有什么东西不起作用以及责怪谁。