0

I am new to ruby 1.9.2. How to generate CSV file in a single ruby script file?

Here, I wrote a ruby script,

require 'rubygems'
require 'pg'
require 'active_record'
require 'csv'

class AttachEmail

def generate_csv
begin
filename = "csvout.csv"
users = User.all
users.each do |u|
    products = Product.find(:all,:conditions=>["user_id=?",u.id])
    CSV.open(filename, 'w') do |csv|
    # header row
user_name = u.name
      csv << ['Report']
      csv << ['Name','Product', 'Item Count']
      products.each do |product|
      csv << [user_name, product.title,product.count]
      end
end
end
rescue Exception => e
  puts e
end
end
generate= AttachEmail.new
generate.generate_csv

When i run this script.it will produce output like below,

         A                    B        C

0      Report
1      Name,Product,Item    Count
2      user1,PD123,10,990   

But I need output like, separate column, Please can you kind me ? Thanks in advance

2

1 Answer 1

6

First of all, you need to swap loops if you are trying to put all the user data in the same file, and not overwrite it for every user:

CSV.open(filename, 'w') do |csv|
  users.each do |u|
    products = Product.find(:all,:conditions=>["user_id=?",u.id])

Next, fix your Excel (I suspect the output is taken from it, right?) to use comma as a separator, not a "space or comma".

Come back with the file contents attached and an example of CSV file which works for you if it still doesn't work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.