Welcome to my blog, hope you enjoy reading
RSS

Friday 18 January 2013

Export data into CSV and download using Servlet


Export data into CSV and download using Servlet


import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class csvdownloadservlet extends HttpServlet
{
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException
{
System.out.println("start");
//res.setContentType("application/octet-stream");
res.setContentType("text/csv");
res.setHeader("Content-Disposition", "attachment; filename=\"TSR1.csv\"");
try
{
// Write the header line
OutputStream o = res.getOutputStream();
String header = "DisplayName,Age\n";
o.write(header.getBytes());

// Write the data lines
Vector<String> records = getRecords(); // Custom to my app
Iterator<String> i = records.iterator();
StringBuffer line = new StringBuffer();
while (i.hasNext())
{
line.append(i.next());
}
o.write(line.toString().getBytes());
o.flush();
}catch(Exception e)
{
System.out.println(e);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request,response);
}
private static Vector<String> getRecords()
{
Vector<String> v = new Vector<String>();
v.add("aaa,");
v.add("26\n");
v.add("bbb,");
v.add("29\n");
return v;
}
}

0 comments: