Create and download CSV file in a Java servlet

前端 未结 3 856
傲寒
傲寒 2020-12-14 22:27

I am working on Java ExtJS application in which I need to create and download a CSV file.

  • On clicking a button I want a CSV file to be downloaded to a client\'
相关标签:
3条回答
  • 2020-12-14 22:54

    I would like add something to the answer by gaurav. I recently had to implment this functionality in a project of mine and using javascript was out of the question becuase we had to support IE 9. What is the problem with IE 9? (Export to CSV using jQuery and html), see the second answer in the link.

    I needed an easy way to convert a ResultSet of a database query to a string which represent the the same data in CSV format. For that I used http://opencsv.sourceforge.net/ which provided an easy way to get a String ot of the ResultSet, and the rest is as above answer did it.

    THe examples in the project soruce folder give good examples.

    0 讨论(0)
  • 2020-12-14 22:59

    First of all you need to get the HttpServletResponse object so that you can stream a file into it.

    Note : This example is something I Wrote for one of my projects and it works.Works on Java 7.

    Assuming you got the HttpServletResponse you can do something like this to stream a file. This way the file will be saved into clients' machine.

    public void downloadFile(HttpServletResponse response){ 
    
            String sourceFile = "c:\\source.csv";
            try {
                FileInputStream inputStream = new FileInputStream(sourceFile);
                String disposition = "attachment; fileName=outputfile.csv";
                response.setContentType("text/csv");
                response.setHeader("Content-Disposition", disposition);
                response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
    
            } catch (IOException e) {
                logger.error("Error occurred while downloading file {}",e);
            }
    }
    

    And the stream method should be like this.

    private long stream(InputStream input, OutputStream output) throws IOException {
    
        try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
            ByteBuffer buffer = ByteBuffer.allocate(10240);
            long size = 0;
    
            while (inputChannel.read(buffer) != -1) {
                buffer.flip();
                size += outputChannel.write(buffer);
                buffer.clear();
            }
            return size;
        }
    }
    

    What this does is, get an inputstream from your source file and write that stream into the outputstream of the HttpServletResponse. This should work since it works perfectly for me. Hope this helps. Sorry for my bad English.

    0 讨论(0)
  • 2020-12-14 23:12

    I got the solution and I am posting it below.

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\"");
        try
        {
            OutputStream outputStream = response.getOutputStream();
            String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, ffffdd, eeee, ffff, gggg\n";
            outputStream.write(outputResult.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
    }
    

    Here we don't need to save / store the file in the server.

    Thanks

    0 讨论(0)
提交回复
热议问题