Exporting CSV Data Via Dataweave in Apex

by Dan Beer - May 30, 2024
Exporting CSV Data Via Dataweave in Apex

Have you ever tried to handcraft CSV in Apex? It isn’t ideal and usually ends up as one big long concatenated list of field names appended to an unbelievably long string:

csvString += contact.FirstName + ',' + contact.LastName + ',' + contact.Email;

Luckily, one great use case for Dataweave in Apex is exporting records via CSV. Salesforce has documented importing via CSV, but another not-so-well-documented feature is the ability to export.

Wait, What is Dataweave?

DataWeave is a programming language designed by MuleSoft for accessing and transforming data, in other words, converting data from one format to another.

It’s designed to make powerful transformations easy to create. You can read more about Dataweave here.

But I Don’t Have Mulesoft!

No problem, we are not using Mulesoft to drive this.

You can create DataWeave scripts as metadata and invoke them directly from Apex. Like Apex, DataWeave scripts are run on the Salesforce servers.

Show Me The Code!

First, you need to create the Dataweave script file. These sit in the dw directory, for example, src/dw/contactsToCsv.dwl:

%dw 2.0
input payload application/java
output application/csv
---
payload map {
 "First Name": $.FirstName,
 "Last Name": $.LastName,
 "Email": $.Email
}

contactsToCsv.dwl

And then the Apex calling code:

DataWeave.Script script = 
    new DataWeaveScriptResource.contactsToCsv();

List contacts = [
   SELECT Id, FirstName, LastName, Email FROM Contact
];

Map<String, Object> args = new Map<String, Object> {
   'payload' => contacts
};

DataWeave.Result dwResult = script.execute(args);
String csvString = dwResult.getValueAsString();

ContactsToCsv.cls
It’s that simple!

Hang On, What About…

… if I want to suppress the CSV header?
Simple. Change your Dataweave output to include ‘header=false‘:
%dw 2.0
input payload application/java
output application/csv header=false
---
payload map {
 "First Name": $.FirstName,
 "Last Name": $.LastName,
 "Email": $.Email
}

contactsToCsv.dwl

 

What if I also want quotes around the data e.g. “Marc”,”Benioff”,”+123456″? We can do that! Add ‘quoteValues=true‘ to your output:
%dw 2.0
input payload application/java
output application/csv header=false,quoteValues=true
---
payload map {
 "First Name": $.FirstName,
 "Last Name": $.LastName,
 "Email": $.Email
}

contactsToCsv.dwl

We are only scratching the surface of what Dataweave can do here, but hopefully you can see how simple this is to implement!

Feedback

As always, please do let me know what you think. Especially if you disagree or see any mistakes then contact me via danb@nebulaconsulting.co.uk.

Related Content


Get In Touch

Whatever the size and sector of your business, we can help you to succeed throughout the customer journey, designing, creating and looking after the right CRM solution for your organisation