Home > Blockchain >  How do I generate a CSV with ANSI encoding using Ruby?
How do I generate a CSV with ANSI encoding using Ruby?

Time:08-24

Currently I'm generating a CSV with UTF-8 encoding from my administrate ui. But swedish letters "åäö" is not shown correctly in excel or in the label printer programs (P-touch Editor 5.4 & Dymo Connect) I'm using.

After talking to their support I've been told the CSV needs to be ANSI encoded. How do I do that?

My code:

  def to_csv
    attributes = %w{full_name street_address postal_code city}

    CSV.generate(headers: true, col_sep: ",") do |csv|
      csv << attributes

      orders.all.each do |order|
        csv << attributes.map{ |attr| order.address.send(attr) }
      end
    end
  end

CodePudding user response:

By default CSV uses Encoding.default_external as encoding, most likely this is UTF-8.

In your case you have to override it, but first you need to know which ANSI encoding you actually need. (What is ANSI format?)

Most likely you can use Windows-1252 or ISO-8859-1.

Then you can set the external encoding of the CSV string like this:

CSV.generate(headers: true, col_sep: ",", encoding: Encoding::ISO_8859_1)
CSV.generate(headers: true, col_sep: ",", encoding: Encoding::WINDOWS_1252)

Strings work, too:

CSV.generate(headers: true, col_sep: ",", encoding: 'ISO-8859-1')
  •  Tags:  
  • ruby
  • Related