function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rudi_HulsbosRudi_Hulsbos 

Create a text file using APEX

Any idea how to create a text file in APEX using values in a list of objects? I have a list of Accounts, the text file must be formatted in a specific format, e.g.. Account Number (1 – 16) right justified, Account Name (17 - 47) left justified, Account Site (47 - 50) right justified.

Best Answer chosen by Admin (Salesforce Developers) 
Rudi_HulsbosRudi_Hulsbos

Thanks for your suggestion, we have decided to export the records from Salesforce and build the file using an external application.

All Answers

sfdcfoxsfdcfox

Something like this:

 

string spaces = '                                   ';
string source = '';
for(object o:objectlist) {
    integer accnumlen = math.min(16,o.accountnumber.length());
    integer accnamelen = math.min(30,o.name.length());
    integer accsitelen = math.min(4,o.accountsite.length());
    source += spaces.substring(0,16-accnumlen); // left pad spaces
    source += o.accountnumber.substring(0,accnumlen); // trim to 16 chars
    source += o.name.substring(0,accnamelen); // trim to 30 chars
    source += spaces.substring(0,30-accnamelen); // pad with spaces
    source += spaces.substring(0,4-accsitelen); // pad more spaces
    source += o.accountsite.substring(0,accsitelen); // trim to 4 chars
    source += '\n';
}

This code assumes that there are no null pointers in your variables. Adjust accordingly.

 

Basically, I make heavy use of substring to create padding and trimming effects. Note that "strings" must be at least as big as your biggest possible padding or you will run into exceptions.

Rudi_HulsbosRudi_Hulsbos

Thanks for your suggestion, we have decided to export the records from Salesforce and build the file using an external application.

This was selected as the best answer