views:

5156

answers:

2

I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP.

I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI.

I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it?

PS: I tried using iconv but had no success.

+5  A: 
ascii_str = yourUTF8text.unpack("U*").map{|c|c.chr}.join

assuming that your text really does fit in the ascii character set.

AShelly
That did it as well and it didn't need to use iconv at all. Thanks!
Dema
+4  A: 

I finally managed to do it using iconv, I was just messing up the parameters. So, this is how you do it:


require 'iconv'

utf8_csv = File.open("utf8file.csv").read

# gotta be careful with the weird parameters order: TO, FROM !
ansi_csv = Iconv.iconv("LATIN1", "UTF-8", utf8_csv).join

File.open("ansifile.csv", "w") { |f| f.puts ansi_csv }

That's it!

Dema