I have an ajax call which calls the ExcelFileServlet
which creates a XSSF Workbook
(Apache POI).
The java script call is as below :
$.ajax({
type: "GET",
url: "./ExcelFileServlet",
async: true,
data: { dataRows: JSON.stringify(dataRows.toArray()) },
success: function(responseText, textStatus, request) {
console.log(responseText);
}
});
The ExcelFileServlet
code is as below:
@WebServlet("/ExcelFileServlet")
public class ExcelFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Gson gson;
private XSSFWorkbook workbook;
public ExcelFileServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//PrintWriter out = response.getWriter();
List<Bean> beanList = new ArrayList<Bean>();
JSONArray arr;
try {
//Processing here to get beanList
//response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//response.setContentType("application/vnd.ms-excel");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"BeanFile.xlsx\"");
response.setStatus(HttpServletResponse.SC_OK);
ExcelUploadFactory euf = new ExcelUploadFactory();
workbook = euf.createExcelFile(beanList); // Creates the workbook here
try(OutputStream os = response.getOutputStream()) {
workbook.write(os);
workbook.close();
os.flush();
os.close();
} catch(Exception E) {
E.printStackTrace();
Configuration.getInstance().getTelemetry().trackException(E);
}
//workbook.write(response.getOutputStream());
} catch (JSONException e) {
e.printStackTrace();
Configuration.getInstance().getTelemetry().trackException(e);
} catch (Exception e) {
e.printStackTrace();
Configuration.getInstance().getTelemetry().trackException(e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Code Here
}
}
I have tried setting up different content types for the Response but I am getting vague characters as the response and the file is not getting downloaded. What change do I need to make for it to enable me to get the excel file as the response?