Saturday, June 1, 2013

Some code borrowed from BalusC.

//ServletCode for CSV Export
public static <T> void writeCsv (List<T> csv, char separator, OutputStream output) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
    System.out.println("Instance NextType: "+csv.getClass().getCanonicalName()+ " Size: "+ csv.size());
    //add headers here
        writer.append("ID").append(separator);
     
        writer.append("LOCATION").append(separator);
     
        writer.append("NAME").append(separator);
     
        writer.append("TYPE").append(separator);
     
        writer.append("FLAG").append(separator);
     
        writer.append("TIME1").append(separator);
     
        writer.append("SYSTIME").append(separator);
     
        writer.append("USERID");
        writer.newLine();

    for (T row : csv) {
            if(row instanceof entities.Item){
                Item item = (entities.Item)row;
                Integer itemid = item.getId();
                writer.append(itemid.toString()).append(separator);
                Date enteredtime = item.getTime1();
                if(time1 == null) {
                    writer.append(" ").append(separator);
                }
                else
                    writer.append(enteredtime1.toString()).append(separator);
                long userid = item.getUserid();
                writer.append(String.valueOf(userid));
.....
            }

        writer.newLine();
    }
    writer.flush();
}

    @EJB
    private beans.ItemFacade ejbFacade;
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Item> listOfObj = new ArrayList<Item>();

        listOfObj = ejbFacade.findAll();
        List<Item> csvList = new ArrayList<Item>();
    List<Item> csv = listOfObj;
    response.setHeader("Content-Type", "text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=\"file"+System.currentTimeMillis()+".csv\"");
    writeCsv(csv, ',', response.getOutputStream());
    }