Anil D
Anil D

Reputation: 2009

Escape Comma from CSV in Ruby

I'm creating a CSV download in my Ruby application which has some Dollar amount fields. These fields has data in cyrrency format like $35,456 and when such data comes in CSV it get seperated into two fiedls , data after comma moved to next column in CSV.

Here is my code to render CSV

Sell Date, Sell Amount
- @rows.each do |row|
  = "#{row[0]},#{number_to_currency(row[1], :precision => 2)}"

Here is the action used to return CSV

def fifolog
  @rows = Report.fifolog()
respond_to do |format|
  format.csv { render csv: {:rows =>@rows }}
end
end

Is there any escape character i can use to escape "," in ruby

thanks

Upvotes: 13

Views: 13064

Answers (2)

Joshua Pinter
Joshua Pinter

Reputation: 47481

Use Ruby's built-in to_csv method.

If you haven't already done so, you'll need to require 'csv'.

Sell Date, Sell Amount
- @rows.each do |row|
  = [ row[0], number_to_currency(row[1], :precision => 2) ].to_csv( row_sep: nil ).html_safe

to_csv is available right on the Array and does all the escaping you'd expect it to do.

row_sep: nil prevents the \n at the end of each row since you're already doing that with each. Try it without that and you'll see that you get an extra blank line. If you were just generating a single CSV string then you'd need to keep the \n to separate the rows.

html_safe prevents the " characters from showing up in your CSV file.

That should do it!

JP

Upvotes: 18

Trevor
Trevor

Reputation: 6689

Use double quotes around values that have a comma:

"$35,456"

Edit: Using FasterCSV, change the following lines:

respond_to do |format|
  format.csv { render csv: {:rows =>@rows }}

to

csv_data = FasterCSV.generate do |csv| 
    csv << ["Sell Date", "Sell Amount"] 

    @rows.each do |row| 
      csv << [row[0],number_to_currency(row[1], :precision => 2)] 
    end 
  end 

  send_data csv_data, 
            :type => 'text/csv', 
            :disposition => "attachment; filename=file.csv"

Upvotes: 6

Related Questions