Create and write content into CSV file / Spread-sheet

Below example will illustrate how to create a csv or excel file and write any desired content into it. In this example we are going to use the FileWriter object and which is available in java.io package.

package com.amzi.xml;

import java.io.FileWriter;
import java.io.IOException;

public class CreateCsvFile {
 private static void generateCsvFile(String fileName) {
  FileWriter writer = null;
  try {
   writer = new FileWriter(fileName);
   writer.append("Name");
   writer.append(',');
   writer.append("ID");
   writer.append('\n');

   writer.append("Amzi");
   writer.append(',');
   writer.append("001");
   writer.append('\n');

   writer.append("Bond");
   writer.append(',');
   writer.append("007");
   writer.append('\n');

   System.out.println("CSV file is created...");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    writer.flush();
    writer.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  String location = "/users/Amzi/test.csv";
  generateCsvFile(location);
 }
}

No comments:

Post a Comment