I want to export the excel file in browser and download the file in browser download location (same as any download that happens in a browser). I'm using following servlet for export the file and it does not shows the downloading or it does not download to the browser default download location. But file has exported to project location.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// PrintWriter out = response.getWriter();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment; filename=filename.xls");
try {
// ExportClass export = new ExportClass();
// export.export();
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
// Create row object
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("AGE");
cell = row.createCell(2);
cell.setCellValue("ID");
cell = row.createCell(3);
cell.setCellValue("NAME");
int i = 2;
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
for (int x = 0; x < students.size(); x++) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue(students.get(x).studentAge);
cell = row.createCell(2);
cell.setCellValue(students.get(x).studentID);
cell = row.createCell(3);
cell.setCellValue(students.get(x).stuntName);
i++;
}
// Write the workbook in file system
OutputStream out = response.getOutputStream();
System.out.println("going to export");
workbook.write(out);
out.close();
System.out.println("exceldatabase.xlsx written successfully");
}
Please help me to figure out the issue. Thanks.