2

我正在努力发送 excel 文件作为对 JAVA 休息服务中下载的 ajax 请求的响应。但编码类型似乎不正确。这是我的java类

@Path("/ExcelExport")
public class ExportExcel {
    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    @Path("/export")
    public Response getBrowserLanguage(String meterdata) throws JSONException
    {
         JSONObject output = new JSONObject(meterdata);
         JSONArray gridArray = output.getJSONArray("finalJsonObj");
         JSONObject gridRow=null;
         ResponseBuilder response=null;
        try {
         final HSSFWorkbook workbook = new HSSFWorkbook();
         HSSFSheet sheet = workbook.createSheet("Sheet1"); 
         String colNames[]=null;
         Row row =null;
         Cell cell = null;
         int cellnum = 0;
         if(gridArray.length()>0){           
             row = sheet.createRow(0);
             gridRow=(JSONObject)gridArray.get(0);
             colNames=JSONObject.getNames(gridRow);
             for (String colName: colNames) {
                 cell = row.createCell(cellnum++);
                 cell.setCellValue(colName);
             }
             for (int i=0;i<gridArray.length();i++) {
                 row = sheet.createRow(i+1);
                 cellnum = 0;
                 gridRow=(JSONObject)gridArray.get(i);
                 for (String colName: colNames) {
                     cell = row.createCell(cellnum++);
                     cell.setCellValue(gridRow.getString(colName));
                 }
             }
         }
         response= Response.ok(new StreamingOutput() {
            @Override
            public void write(OutputStream outputStream) throws IOException,
                    WebApplicationException {
                workbook.write(outputStream);
            }
        },"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");     
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response.header("Content-Disposition","attachment; filename=export.xls").build();
    }
}

在 Xmlhttprequest 的成功函数中,我执行以下操作:

window.location = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheetExpor,' + xmlhttp.responseText;

excel 文件打开,但编码似乎不同,因此它显示了一些垃圾文本。

提前致谢

4

2 回答 2

0

这是 excel 的有效 MIME 类型。

对于 BIFF .xls 文件

application/vnd.ms-excel

来源:http: //blogs.msdn.com/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx

Excel2007及以上.xlsx文件

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
于 2013-07-02T09:09:05.153 回答
0

从您的评论中,我了解到您希望用户下载 excel 文件而不是内联显示它。您可以在 Servlet 中添加以下代码。

response.setContentType("application/vnd.ms-excel");  
response.setHeader("Content-disposition","attachment; filename=someFile.xls");  
于 2013-07-02T15:00:02.413 回答