3

I want to create an Excel file from a method in Java and download it in a browser.

I have found an example on this post where you create the Excel file, but I want to create the .xls file and download it from a web browser.

How can I do that?

7
  • 1
    Do you mean you would like to download the file in a web browser? Or you would like to visualize the excel file in a web browser? Commented Sep 23, 2015 at 16:00
  • Just download the created file in a location in my PC, just like a regular download... Commented Sep 23, 2015 at 16:02
  • 1
    Where will the file be? Locally on your machine, or somewhere on a server? Commented Sep 23, 2015 at 16:09
  • Locally in my machine... Commented Sep 23, 2015 at 16:10
  • Just type this in your browser : file:///C:/path_to_your_file.xls then you will download the file... It has nothing to do with Java or Excel though. Commented Sep 23, 2015 at 16:12

3 Answers 3

5

I finally found a solution for my problem...!!

This is working for me:

       @RequestMapping("/downloadFile")
       public void downloadFile(HttpServletRequest request, HttpServletResponse response) {             

       try {

            String fileName = "C:/excelFile.xls";
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("firstSheet");

            HSSFRow rowhead = sheet.createRow((short) 0);
            rowhead.createCell(0).setCellValue("No.");
            rowhead.createCell(1).setCellValue("Name");
            rowhead.createCell(2).setCellValue("Address");
            rowhead.createCell(3).setCellValue("Email");

            HSSFRow row = sheet.createRow((short) 1);
            row.createCell(0).setCellValue("1");
            row.createCell(1).setCellValue("Carlos");
            row.createCell(2).setCellValue("Costa Rica");
            row.createCell(3).setCellValue("[email protected]");

            FileOutputStream fileOut = new FileOutputStream(fileName);
            workbook.write(fileOut);
            fileOut.close();
            System.out.println("Your excel file has been generated!");

            //Code to download
            File fileToDownload = new File(fileName);
            InputStream in = new FileInputStream(fileToDownload);

            // Gets MIME type of the file
            String mimeType = new MimetypesFileTypeMap().getContentType(fileName);

            if (mimeType == null) {
                // Set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            System.out.println("MIME type: " + mimeType);

            // Modifies response
            response.setContentType(mimeType);
            response.setContentLength((int) fileToDownload.length());

            // Forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", fileToDownload.getName());
            response.setHeader(headerKey, headerValue);

            // obtains response's output stream
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = in.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            in.close();
            outStream.close();

            System.out.println("File downloaded at client successfully");


        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to trigger a Java process from a Web Browser (HTTP request), then you need an application server (like Tomcat) to accept your HTTP request and execute some server-side code (Servlet). A main method like in the example cannot be launched by a HTTP request. Look here if you never wrote a Servlet before.

1 Comment

Now, you see how important it is to be clear in the original question.
-1

This has nothing to do with Excel, but this post shows how to download a file from a Spring MVC controler.

    @RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
    public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response) {
    try {
      // get your file as InputStream
      InputStream is = ...;
      // copy it to response's OutputStream
      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.