【发布时间】:2016-10-19 11:04:42
【问题描述】:
我正在开发一个 GWT 应用程序,该应用程序为公司中的每个团队提供关于他们必须做什么的概览。 该程序正在运行,但现在我们希望您可以下载的 Excel 表格是 .xlsx 而不是 .xls。 整个项目对我来说都是新的,我认为自己是 GWT 的初学者。
在代码中,当为 Excel 表格指定文件名时,末尾有一个+".xls"。当我将其更改为+".xlsx" 并测试应用程序时,下载仍然有效。但是,当我尝试在 Excel 中打开文件时,它会显示一条错误消息并告诉我文件已损坏。 (.xls 有效)
您能解释一下 GWT 中如何使用 serverSite 生成的 Excel 进行下载吗? 也许您有一些想法是什么导致文件损坏 (可惜这个应用程序的程序员在放假,所以我不能问他)
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();
}
}
}
【问题讨论】:
-
您能提供您要更改的代码吗?听起来您只是在更改 http 响应中的文件名,而不是内容类型。
-
@Akkusativobjekt 问题是我真的不允许在这里发布代码......而且整个项目相对较大,它有超过 80 个课程,目前我试图弄清楚我必须在哪里改变一些东西......遗憾的是我不能问我的同事,因为他正在度假......如果我找到代码部分,我会分享它
-
如果它是一个 HttpServlet 寻找类似 response.setContentType("application/vnd.ms-excel");
-
@Akkusativobjekt 我在我找到“response.setContentType...”的地方添加了代码 - 你能向我解释一下下载是如何使用 serverlet 工作的吗?或者你能推荐一个好的教程吗?