Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quote all fields in CSV output

Tags:

ruby

csv

@out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w")
CSV::Writer.generate(@out) do |csv|
  csv << ["01", "02", "test"]
end
@out.close

When i run above code it stores the values in CSV as

01, 02. test

I want them to store as

"01", "02", "test"

like image 491
vasu Avatar asked Apr 29 '11 11:04

vasu


People also ask

How do I stop excel from adding unwanted quotation marks to my exported CSV file?

To do this, select the column of data that has the extra quote marks, then go to the “Data” tab and click “Text to Columns.” In the “Text to Columns” wizard, select “Delimited” and click “Next.” Then, uncheck the “Tab” option and check the “Other” option.

How do you quote in CSV?

You can put quotes, dashes and spaces in the CSV file. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes. If a field's value contains a double quote character it is escaped by placing another double quote character next to it.


1 Answers

Change

CSV::Writer.generate(@out)do |csv|

to

CSV::Writer.generate(@out, {:force_quotes=>true}) do |csv|
like image 178
steenslag Avatar answered Oct 23 '22 11:10

steenslag