How to Export CSV in Drupal 10 (2025) – Step-by-Step Guide

🔥 How to Export CSV in Drupal 10 (2025) – Step-by-Step Guide

Need to **export data to CSV** in **Drupal 10**? This guide will show you how to create a **CSV export feature** using a custom module with real examples. 🚀

✅ Step 1: Create a Custom Module

To start, create a **custom module** inside the "modules/custom" directory of your Drupal installation.

modules/custom/csv_export/csv_export.info.yml

✅ Step 2: Define the Module

Now, define your **module information file** so that Drupal recognizes it properly.

name: 'CSV Export' type: module description: 'A module to export data in CSV format' package: Custom core_version_requirement: ^10

✅ Step 3: Create a CSV Controller

Inside your module, create a **controller file** that will generate the CSV file.

modules/custom/csv_export/src/Controller/CSVExportController.php

✅ Step 4: Define a Route for CSV Download

Set up a **routing file** in your module to define the **URL endpoint** that users will visit to download the CSV file.

path: '/csv-export' defaults: _controller: '\Drupal\csv_export\Controller\CSVExportController::exportCSV' _title: 'Export CSV' requirements: _permission: 'access content'

✅ Step 5: Implement CSV Export Logic

Modify your **CSVExportController.php** file to fetch data from the database and format it into a downloadable CSV file.

public function exportCSV() { $rows = [ ['ID', 'Name', 'Email'], [1, 'John Doe', 'john@example.com'], [2, 'Jane Smith', 'jane@example.com'], ]; $handle = fopen('php://output', 'w'); foreach ($rows as $row) { fputcsv($handle, $row); } fclose($handle); return new Response($output, 200, [ 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="export.csv"', ]); }

✅ Step 6: Enable the Module

Once your module is set up, enable it in Drupal using the admin panel.

✅ Step 7: Test the CSV Export

Visit the **/csv-export** URL on your Drupal site, and if everything is correct, your CSV file will be downloaded automatically.

🚀 Conclusion

By following this guide, you have successfully implemented **CSV export** in **Drupal 10** with a custom module. This solution works perfectly for exporting user data, orders, or any other custom data in CSV format.

🔗 Visit Developer Sahayak

0 Comments