June 15, 2012

How to export data to CSV file ) Java



CSV is stand for Comma-separated values, CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines. In other words,
A CSV file is commonly known as a Comma Delimited File or a Character Separated File. It is a text file that has a specific format which allows saving of text in organized manner. This format known as a flat table, is very simple. Each row contains one record of information. The character used to distinguish each piece of data within each record is most commonly used a comma ",".
More detail please check http://en.wikipedia.org/wiki/Comma-separated_values
Please take a look at a CSV sample,
Display Name, Age, Hand Phone Micheal , 30, 0123456789 Bill, 25, 0129876543

Actually CSV is just like a text file with a certain delimited like comma "," or semi-comma ";" or any other delimited character you want. Here i will show how to use java to export data or writing data into a CSV file. This sample is very simple and straight froward, it just use java FileWriter object to create a normal text file (CSV file).



import java.io.FileWriter; 
import java.io.IOException; 
public class GenerateCsv  {     public static void main(String [] args)     {   
   generateCsvFile("c:\\test.csv");     }      
private static void generateCsvFile(String sFileName)     {  
 try   {       FileWriter writer = new FileWriter(sFileName);      
    writer.append("DisplayName");    
    writer.append(',');      
    writer.append("Age");    
    writer.append('\n');      
    writer.append("MKYONG");   
    writer.append(',');   
    writer.append("26");      
    writer.append('\n');      
    writer.append("YOUR NAME");  
    writer.append(',');    
    writer.append("29");   
    writer.append('\n');          //generate whatever data you want    
    writer.flush();   
    writer.close();   }  
 catch(IOException e)   {        e.printStackTrace();   }   
   }  }
Second example:
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CsvFile extends HttpServlet {
public void doGet (HttpServletRequest request,
    HttpServletResponse response)
throws ServletException,IOException  {
try
{
  PrintWriter out = response.getWriter();
  String filename = "c:\\csv\\myfile.csv";
  FileWriter fw = new FileWriter(filename);

  fw.append("Employee Code");
  fw.append(',');
  fw.append("Employee Name");
  fw.append(',');
  fw.append("Employee Address");
  fw.append(',');
  fw.append("Employee Phone");
  fw.append(',');
  fw.append("Employee ZipCode");
  fw.append('\n');

  fw.append("E1");
  fw.append(',');
  fw.append("Vineet");
  fw.append(',');
  fw.append("Delhi");
  fw.append(',');
  fw.append("224277488");
  fw.append(',');
  fw.append("110085");
  fw.append('\n');

  fw.append("E2");
  fw.append(',');
  fw.append("Amar");
  fw.append(',');
  fw.append("Delhi");
  fw.append(',');
  fw.append("257765758");
  fw.append(',');
  fw.append("110001");
  fw.append('\n');

  fw.append("E3");
  fw.append(',');
  fw.append("Amit");
  fw.append(',');
  fw.append("Delhi");
  fw.append(',');
  fw.append("257685858");
  fw.append(',');
  fw.append("110005");
  fw.append('\n');
  fw.flush();
  fw.close();
  out.println("<b>Csv file Successfully created.</b>");

}
catch (Exception ex) {
ex.printStackTrace ();
}
}
}






3 comments:

  1. Vitamin A regulates the sex hormone progesterone, which is important when looking
    for the optimum in sexual health. Vitamin B helps to improve the
    blood circulation and stamina. Vitamin C helps to
    produce hormones needed for a healthy sex life and fertility.
    It helps to increase sperm count and their mobility, strengthens capillaries as well as veins and
    reduces blood cholesterol. Vitamin E promotes the creation of prostaglandins,
    hormones important to a healthy sex drive.

    Checkout this web resource for more http://www.nancefornevada.com/.

    ReplyDelete
  2. And if it does revalue at or near that rate, those roulette investors is going to be laughing all the
    way to the bank. They just seem like crap since they have not been taken care of.
    Whichever gets elected, America will survive and thrive.

    Feel free to visit my page ... best dating course for men

    ReplyDelete
  3. This task would be much simpler by using Jackson extension from here:

    https://github.com/FasterXML/jackson-dataformat-csv

    which would allow converting between simple Java Objects (POJO / bean) and CSV.

    ReplyDelete

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts