[英]Apache Poi the Excel(.xlsx) file is corrupted. (Using XSSF)
[英]GWT Download Excel .xlsx gives me a corrupted file
我正在開發一個 GWT 應用程序,它為公司中的每個團隊提供了關於他們必須做什么的概述。 該程序正在運行,但現在我們希望您可以下載的 Excel 表格是 .xlsx 而不是 .xls。 整個項目對我來說都是新的,我認為自己是 GWT 的初學者。
在代碼中,當為 Excel 表指定文件名時,末尾有一個+".xls"
。 當我將其更改為+".xlsx"
並測試應用程序時,下載仍然有效。 但是,當我嘗試在 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 模式,因此你的服務器知道這個 servlet 應該處理一個特定的 url。
您展示的 servlet 首先從會話中提取文件名和文件內容。 另外准備好http響應並寫出文件內容。 現在您只需要將響應的內容類型替換為 xlsx 的內容類型。
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
處理 http 響應的瀏覽器現在將下載識別為 .xlsx 文件。 正如您所注意到的,文件擴展名在此步驟中並不重要。
當 servlet 的原始程序員從他的假期回來時,您應該/可以推薦他使用response.sendError()
(帶有適當的 http 狀態代碼)而不是e.printStackTrace()
。 這樣 servlet 的用戶就可以更好地了解是否有問題以及該怪誰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.