I'm trying too hard to send excel file as a response to an ajax request for download in JAVA rest service. But the encoding type seems to be incorrect . Here is my java class
@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();
}
}
And in the success function of Xmlhttprequest I do the following :
window.location = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheetExpor,' + xmlhttp.responseText;
The excel file opens but the encoding seems to be different hence it shows me some junk text .
Thanks in Advance