Load comma seperated values (CSV) from a file into memory

From CodeCodex

Implementations[edit]

Java[edit]

The following code uses the free library CSVReader. You must download this library to use the code below.

Sample Code[edit]

	CsvReader reader = new CsvReader("products.csv");

	reader.readHeaders();

	while (reader.readRecord())
	{
		String productID = reader.get("ProductID");
		String productName = reader.get("ProductName");
		String supplierID = reader.get("SupplierID");
		String categoryID = reader.get("CategoryID");
		String quantityPerUnit = reader.get("QuantityPerUnit");
		String unitPrice = reader.get("UnitPrice");
		String unitsInStock = reader.get("UnitsInStock");
		String unitsOnOrder = reader.get("UnitsOnOrder");
		String reorderLevel = reader.get("ReorderLevel");
		String discontinued = reader.get("Discontinued");
		
		// perform program logic here

	}

	reader.close();

Source File Format[edit]

	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
	...

Ruby[edit]

require "csv"
csv_file = "test.csv"

CSV.foreach(csv_file) {|row| p row}

table = CSV.readlines(csv_file)
p table[1][1]

# The version 1.9 Later
csv = CSV.read(csv_file, :headers=>true)
p csv.headers
csv.headers.each_with_index do |head,i|
  print "#{i} #{head} \t: "
  p csv[head]
end
p csv['QuantityPerUnit']

The contents of the CSV file

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