2

I have this string %22%00%41%00%22%00%09%00%22%00%42%00%22%00 which is the UTF-16LE equivalent of "A"\t"B". (The \t is a Tab char.)

I am trying to construct a Blob and then a URL for it, but the output isn't decoded to proper entities.

var blob=new Blob([stringHere],{type:'text/csv;charset=UTF-16LE;'});
var blobUrl=URL.createObjectURL(blob);

Is there anyway to tell the Blob the string encoding so that it looks properly when opened in Excel (in this particular case)?

I need UTF-16LE, otherwise using UTF-8 will result in Excel no parsing the .csv file properly.

Thanks.

1 Answer 1

2

It looks like you need a utf-16 le bom in the file, which you can't do with a string in js, so you'll have to use a byte array. See example below

var stringHere = '%ff%fe%22%00%41%00%22%00%09%00%22%00%42%00%22%00';
var byteArray = [];
stringHere.replace(/([0-9a-f]{2})/gi, function(d){
    byteArray.push(parseInt(d, 16));
});
var blob=new Blob([new Uint8Array(byteArray)],{type:'text/csv;charset=UTF-16LE;'});
var blobUrl=URL.createObjectURL(blob);
Sign up to request clarification or add additional context in comments.

10 Comments

Hi Musa, thanks. That doesn't seem to output UTF-16LE though. Like you said, I need that encoding for Excel to interpret CSVs properly. BOM is for non-ASCII chars. It seems to me the type thing only looks at MIME Type and ignores the charset specified.
@Francisc I tried it and it worked for me, if you put the blob url in the browser it will download the file, just give it a csv extension and open it with excel.
And you actually see "A" and "B" in different columns?
You're right, it does work. I must have done a mistake when I first tested.
Maybe, I don't know. But thing to remember, each entry in the Uint8Array represents a byte not a character. A utf-8 character can be 1-4 bytes long. The url encoding encoded each byte which made it easy to convert it to an typed array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.