Author Topic: Action in Struts2 (Java) for ExportToExcel  (Read 5131 times)

jibag

  • Pro Deluxe
  • Newbie
  • *
  • Posts: 1
    • View Profile
Action in Struts2 (Java) for ExportToExcel
« on: December 04, 2013, 01:55:44 pm »
There are server code examples ins ASP.NET y PHP to manage export to Excel.
I would need some example in Java code; more specifically in an Struts2 action.

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6310
    • View Profile
Re: Action in Struts2 (Java) for ExportToExcel
« Reply #1 on: December 06, 2013, 11:28:11 pm »
Here is the relevant Java code for a Spring controller.

Code: [Select]

    @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();
    }

« Last Edit: December 06, 2013, 11:33:31 pm by paramquery »