ntstha
ntstha

Reputation: 1173

How to download csv file without writing it using OpenCsv

I am using OpenCsv API and now i am stuck in some problem.Here's my code

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            List<UserRegData> userRegDataList = new ArrayList<UserRegData>();
            HttpSession session = request.getSession();
            userRegDataList = (List<UserRegData>) session.getAttribute("referralData");
            List<String[]> dataToWrite = new ArrayList<String[]>();
            String csv = "E:\\carewave_backup\\csv\\UserReferral.csv";
            CSVWriter writer = new CSVWriter(new FileWriter(csv));

            for (UserRegData obj : userRegDataList) {
                dataToWrite.add(new String[]{obj.getReferred_by_name(), obj.getInvitee_name(), obj.getInvitee_email(), obj.getInvitee_date(), obj.getIsInviteeRegistered(), obj.getDate_of_invitee_registered()});
            }
            writer.writeAll(dataToWrite);
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

This servlet basically retrieves list from session and writes it to csv file.This servlet is triggered after user clicks download csv button.Now what i need is, browser should give a download dialogue.Is there anyway to download it in csv format without writing it to file first?.

Upvotes: 1

Views: 2785

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

I assume you're asking about how to stream the output on the server directly to the client without writing it first to a temp file on the server.

You don't need to write the data to a file first.

  1. Set the resonse content-type to text/csv
  2. Call getOutputStream() on the response object
  3. Write the contents of dataToWrite as individual lines to the output stream

No disk file needed.

Upvotes: 2

Related Questions