I want to generate a csv attachement and force ANSI encoding how can i do that? Code to create my attachement:

string rows = 'column1;column2;column3'+'\n'+'a;b;c'
Attachment attachment = new Attachment();
attachment.Body = Blob.valueOf(rows);
attachment.Name = 'file.csv';
attachment.ParentId = recordId;
insert attachment;

I've tried charset=ANSI it didn't generate a csv.

1 Answer 1

  1. You can't. Salesforce Apex always treats strings as UTF-8 and has no functionality for working with or converting between text encodings whatsoever. While you can implement gimmicky conversions in some cases using the confusingly-named EncodingUtil class (which doesn't deal with text encodings) or even with regular expressions (to strip specific character classes only), it's going to be rather hacky and isn't something I'd particularly trust for an enterprise system. Instead, I would strongly recommend doing this conversion on the target system or in middleware, where it can be done correctly.

  2. There is no encoding called "ANSI" (which just stands for "American National Standards Institute"). Possibly you mean ASCII or Windows Codepage 1252. Both of these encodings do not map all of the characters represented by UTF-8, so this would be a destructive operation.

  3. This code is a simple example, but it's important to note that if you are generating CSV by simple concatenation as shown here you are probably not correctly implementing RFC 4180 by handling embedded commas, newlines, and quote characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.