user2124871
user2124871

Reputation: 813

PrintWriter to write to CSV - New line not working?

I've tried just about everything I could find online and on this particular site and none of these options are working. I'm looping through a list of objects and creating a CSV file. I'd like to break at each object entry, but no luck so far.

Here is what I have currently:

    String value = FacesContext.getCurrentInstance().
            getExternalContext().getRequestParameterMap().get("cityId");
    
    String seperator = System.getProperty("line.separator");
    
    try {
        
        PortletResponse response1 = (PortletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
        HttpServletResponse resp = PortalUtil.getHttpServletResponse(response1);
        resp.setHeader("Content-Type", "text/csv");
        resp.setHeader("Content-disposition", "attachment;filename=myFile.csv");

       List<Person> people = ppApi.getPeopleByCityId(Long.parseLong(value));
        
       PrintWriter out = resp.getWriter();
        
       for(Person pp : people) {
            
           out.print(pp.getFirstName() + ",");
           out.print(pp.getLastName() + ",");
           out.print(pp.getEmail() + ",");
           out.print(pp.getPhone() + "%%n");
           out.print("\r\n");
           out.print("\n\r");
           out.print("\n");
           out.print("\r");
           out.print("\\r\\n");
           out.print("\\n");
           out.print("\\n\\r");
           out.print(seperator);
           out.println('\n');
           out.println("%n");
           out.println("%%n");
        }
        
        //Close the output stream
        out.flush();
        out.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }

So none of those things are working. My output looks something like this:

jeff,smith,[email protected],555-123-1234 rick,smith,[email protected],123-123-1233

Should look like:

jeff,smith,[email protected],555-123-1234

rick,smith,[email protected],123-123-1233

Upvotes: 0

Views: 2051

Answers (1)

Andremoniy
Andremoniy

Reputation: 34900

Please, do not invent a bicycle and use Java CSV library. It will eliminate all your problems.

Upvotes: 1

Related Questions