java4all@1986 java. Powered by Blogger.

How to read data into csv file?

>> Tuesday, May 31, 2011

For example we are having an excel sheet like below
File Format:
ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued
1,Chai,1,1,10 boxes x 20 bags,18,39,0,10,FALSE
2,Chang,1,1,24 - 12 oz bottles,19,17,40,25,FALSE

To read Data from csv file we will use CsvReader class.

import java.io.FileNotFoundException;
import java.io.IOException;

import com.csvreader.CsvReader;

public class CsvReaderExample {

 public static void main(String[] args) {
  try {
   CsvReader products = new CsvReader("products.csv");
  
   products.readHeaders();//This method is used to headers from csv file

   while (products.readRecord()) //This method is used to read data from records
   {
    String productID = products.get("ProductID");
    String productName = products.get("ProductName");
    String supplierID = products.get("SupplierID");
    String categoryID = products.get("CategoryID");
    String quantityPerUnit = products.get("QuantityPerUnit");
    String unitPrice = products.get("UnitPrice");
    String unitsInStock = products.get("UnitsInStock");
    String unitsOnOrder = products.get("UnitsOnOrder");
    String reorderLevel = products.get("ReorderLevel");
    String discontinued = products.get("Discontinued");
    
    // perform program logic here
    System.out.println(productID + ":" + productName);
   }
 
   products.close();
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }

}


This is the simple way to read data from csv file.

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP