我正在努力发送 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 文件打开,但编码似乎不同,因此它显示了一些垃圾文本。
提前致谢