我正在努力发送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文件打开但编码似乎不同,因此它显示了一些垃圾文本。
先谢谢
答案 0 :(得分: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
答案 1 :(得分:0)
从您的评论中,我了解您希望用户下载excel文件而不是内联显示。您可以在Servlet中添加以下代码。
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment; filename=someFile.xls");