3

I have an interesting request:

We sold a region to another company, and we'd like to give the departing salespeople their data. It's a simple query to get everything the 4 users from that region created or own by userid.

The request is, "Get every account, contact, etc. that they had an activity on" for export.

Tooling-wise, I've got the excel add-in and Jitterbit dataloader, which is very cool.

I know how to do this in apex (relationship query up related records on activity) but I'm not sure how to go from that to CSV. Advice?

1
  • 3
    Is giving them access to get their own data an option? report + export? this way, what they don't get, they can't come to you complaining ^^
    – Saariko
    Sep 19 '12 at 15:10
2

If there isn't a ton of data for the four users you could just write it out to a VF page. You can format it for Excel with different sections as well. See the Using Content Types documentation.

<apex:page controller="MyDataExportController" contenttype="application/vnd.ms-excel#MyDataExport.xls">
   <apex:pageBlock title="Owned Contacts">
      <apex:pageBlockTable value="{!Contacts}" var="contact">
         <apex:column value="{!contact.Owner.Name}"/>
         <apex:column value="{!contact.FirstName}"/>
         <apex:column value="{!contact.LastName}"/>
         <apex:column value="{!contact.Phone}"/>
      </apex:pageBlockTable>
      <!-- other types of records -->
   </apex:pageBlock>
</apex:page>

Alternatively, you could just use a flat unformatted csv:

<apex:page controller="MyDataExportController" contenttype="text/csv#MyDataExport.csv">
    <!-- write the header row -->
    <!-- write out all rows that you gathered in the controller -->
</apex:page>
1

This could be done through Apex Batch, although you'll need a separate batch class for each object to look for, unless you want to add the target object as a parameter, or rewrite and redeploy the batch for each separate object. It could also be run for all 4 users at once, with 4 csvs, if you prefer.

  • Be sure to use Database.stateful in the class declaration
  • Take a userid as public Id variable or constructor parameter, unless you want to hard code it.
  • Keep a running private String variable to store the CSV
  • Querylocator: All Accounts [or Contacts or whatever] with related Tasks and Events that are owned or created by the specified user.
  • For each Account, skip if there are no matching Tasks or Events. Otherwise, record the Account as a row in the persistent String variable in CSV format.
  • In the finish() of the batch, email that CSV somewhere as an attachment.

My only concern here is if you have millions of records that will end up in that CSV; you may start to run into heap size or attachment size issues.

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.