Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write into CSV file properly

Tags:

ruby

csv

i am using ruby 1.9.2 and also use its csv library.I want to write in csv properly just

like this

name,country_code,destination,code
Afghanistan,93,Bamain,51
Afghanistan,93,Bamain,52
Afghanistan,93,Bamain,53
Afghanistan,93,Parwan,91

My code is this

def export_data
  @coun = Country.all(:limit => 10)
  header = "name,country_code,destination,code"
  file = "my_file.csv"
  File.open(file, "w") do |csv|
    csv << header
    @coun.each do |c|
      csv << [c.name, c.country_code, c.user_id, c.subscriber_id]       
      # How puts line break here
    end
  end
  send_file(file)
end

I have mention above how puts i line break there in CSV file and also omit this sigh which

covers every row in CSV"[]"

 Like   ["Finland",1,1,2334]

Thanks in advance..

like image 675
Kashiftufail Avatar asked May 22 '12 13:05

Kashiftufail


People also ask

How do I write to CSV?

Steps for writing a CSV file First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.


2 Answers

I think general CSV writer will be good enough for you:

require 'csv'
file = "my_file.csv"
CSV.open( file, 'w' ) do |writer|
  @coun.each do |c|
    writer << [c.name, c.country_code, c.user_id, c.subscriber_id]
  end
end
like image 104
ABrukish Avatar answered Oct 08 '22 14:10

ABrukish


csv << "\n"

Stackoverflow requires 30 characters in an answer, but I don't know what more to say.

like image 21
Marlin Pierce Avatar answered Oct 08 '22 15:10

Marlin Pierce