csv, xls and utf8 fail



4 Comments

Share




In case u need to save utf8 data to a csv or xls file, mind that those formats do not support utf8 encoding.
Say, u’ve got to save a cyrillic text to a csv file:


// A sample cyrillic, bulgarian text, for exmaple
var utf8String:String = "Аз съм българче. Обичам наште планини зелени...";

// Try to save the file in utf8 charset and then
// open it with Microsoft Excel
var file:FileReference = new FileReference();
file.save(utf8String, "utf8_test.csv");

And here’s the result:

But don’t hurry to google for an as3 charset encoding library, as there’s a simple way to solve this issue:


// A sample cyrillic, bulgarian text, for exmaple
var utf8String:String = "Аз съм българче. Обичам наште планини зелени...";

// csv, xls appear to work only with the ascii
// and windows-like charsets, so as the string is
// cyrillic, we'll use the cyrillic (Windows) charset 'windows-1251'
// which codename's 'x-cp1251' according to the adobe's as3 reference.
var bytes:ByteArray = new ByteArray();
bytes.writeMultiByte(utf8String, "x-cp1251");

var file:FileReference = new FileReference();
file.save(bytes, "cp1251_test.csv");

Now we got the expected result:


Really simple, but still there might be someone who’d need it.

4 Comments (+add yours?)

  1. Wesley
    May 10, 2010 @ 08:27:02

    FYI Open Office allows you to save a CSV file to a specific encoding.

  2. jloa
    May 10, 2010 @ 14:37:39

    Yeah, but the thing is to make those files readable in any software.

  3. Kirill
    May 17, 2011 @ 06:10:42

    Thank you a lot! I need it. )

  4. jloa
    May 18, 2011 @ 06:21:58

    u are welcome :)

Leave a Reply

Spam protection by WP Captcha-Free