how to export the data in a list to a CSV file in the server side?

旧城冷巷雨未停 提交于 2019-12-25 07:30:36

问题


I have a list of Users and Non-users list which I am putting it in a jsp page by using a for loop and iterating thru html table and . How do I export the data to CSV at the server side. Exporting the data to CSV in the client side is complicated. I have very less knowledge wrt to J2EE. So please help me with this.If you can suggest me an approach, I can follow that..


回答1:


i was able to do this.

Req:On clicking a button in jsp it should export to CSV

jsp code

 <div>

  <input type="button" name="exporttocsv"  onclick="window.open('${pageContext.request.contextPath}/GetUserDetails?exporttocsv=yes','toolbar=no','location=no','status=no','menubar=no','scrollbars=yes','resizable=yes','width=10','height=100');" value="Export to CSV"/>
</div>

GetUserDetails is my servlet.

Servlet side code.

        protected void doGet(HttpServletRequest request, HttpServletResponse response)                         throws ServletException, IOException {

    // TODO Auto-generated method stub

    System.out.println("here inside get method");

    String clickevent=request.getParameter("exporttocsv");


    if(clickevent!=null &&clickevent.equalsIgnoreCase("yes"))
    {

        System.out.println("IN here....... download csv file...");
       //Getting the list from a session and iterating through the list
        HttpSession session = request.getSession();
                List<User> nonusers =          (List<User>)session.getAttribute("nonUserList");

        response.setHeader("Content-type","application/csv");
        response.setHeader("Content-disposition","inline; filename=test.csv");
        PrintWriter out = response.getWriter(); 
        out.println("Device Name,Non-Users");
        for(User nonUser: nonusers)
        {
        out.println(nonUser.getDeviceName()+","+ nonUser.getCecId());
           }

        out.flush();  
        out.close();  


    }

Thanks for your help!!


来源:https://stackoverflow.com/questions/23836728/how-to-export-the-data-in-a-list-to-a-csv-file-in-the-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!