Export SOQL Query as CSV
This demonstrates how to build a custom SOQL query export tool using Apex and Visualforce that allows users to create dynamic SOQL queries and export the results as CSV files. It addresses limitations with standard reports by enabling complex or custom queries to be run and results downloaded easily. The solution uses a custom metadata/config object to store queries, an Apex controller to run them and generate CSV content, and a Visualforce page to output and force file downloads. Salesforce teams can replicate this pattern to offer flexible data exports beyond standard reporting capabilities.
- Use a custom object to store and manage dynamic SOQL query configurations.
- Leverage controller.addFields() to include all dynamic fields for standard controller extensions.
- Construct SOQL queries dynamically with optional WHERE, ORDER BY, and LIMIT clauses.
- Output CSV content via a Visualforce page with appropriate contentType to prompt file download.
- Use readOnly attribute on Visualforce pages to increase query record limits to 10,000.
Hey guys, Long time no blog! Sorry about that, been kind of busy and honestly haven’t had too many interesting tidbits to share. However, I think I have something kind of neat to show you. I had a project recently where the user wanted to be to create a custom SOQL query and export the results as a CSV file. I don’t know why they didn’t want to use regular reports and export (my guess is they figured the query may be too complex or something) but it sounded fun to write, so I didn’t argue. Breaking this requirement down into it’s individual parts revealed the challenges I’d have to figure out solutions for: 1) Allow a user to create a custom SOQL query through the standard interface 2) Extract and iterate over the fields queried for to create the column headings 3) Properly format the query results as a CSV file 4) Provided the proper MIME type for the visualforce page to prompt the browser to download the generated file As it turns out, most of this was pretty easy.