Sampat Badhe
Sampat Badhe

Reputation: 9075

Rails CSV Export - leading zeros are ignored by CSV reader

I have code that creates a csv for address.

The problem is that the zipcodes that have a leading zero are exported properly, but when the csv is open in Excel, the leading zero on zipcodes is removed.

addresses = [["123 Street", "New York", "0123", "USA"], ["421 Street", "New York", "0233", "USA"]]
CSV.open(csv_file, "w", force_quotes: true) do |csv|
  csv << [street_address, city, zipcode, state]
  addresses.each do |address|
    csv << address
  end
end

Is there a way to export a number as a string from a csv, which can be read by excel reader without removing leading zeros?

Upvotes: 1

Views: 1845

Answers (1)

Danny_ds
Danny_ds

Reputation: 11406

You can add a ="" to your exported field:

"123 Street","New York",="0123","USA"

This should preserve the leading zero's in Excel.

Upvotes: 1

Related Questions