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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With