Here is the relevant Java code for a Spring controller.
@RequestMapping(value = "/excel", method = RequestMethod.POST)
public @ResponseBody String excel(String excel, String extension) throws IOException {
if (extension.equals("csv") || extension.equals("xml")) {
String filename = "pqGrid." + extension;
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(excel);
bw.close();
return filename;
} else {
return "";
}
}
@RequestMapping(value = "/excel", method = RequestMethod.GET)
public void excel(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+filename);
File file = new File(filename);
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[1024];
while (fileIn.read(outputByte, 0, 1024) != -1) {
out.write(outputByte, 0, 1024);
}
fileIn.close();
out.flush();
out.close();
}