Drupal - How to export users to a CSV file?

Yes, Views data export is your best choice.

Create a view displaying users and add a page display. Add the fields you want in your export and change any additional settings you want.

Then add a display of type Data export, and set it to attach to the Page display. This way it'll add a link to the file download to that page (You can probably also skip the Page display and only add a Data export display with a path defined).

Choose your export format (CSV) under format settings. If you have a lot of users, make sure to choose batch operation under 'Data export settings'.

It's also a good idea to require a specific permission or role to access the view.


Yes, the Views Data Export is the right module, but if you've big data files, you've to increase proper PHP limits, such as: PHP max_execution_time and memory_limit, unless you're using batch process, so you should be fine. You should increase the limits especially when using export via drush which is supported (note it's using separate PHP settings file).

To export users using custom function, check: How can I export all users in a CSV format?

which is basically the following custom code which you can use within some callback function:

drupal_add_http_header('Content-Type', 'text/csv');
drupal_add_http_header('Content-Disposition', 'attachment; filename=users.csv');
$results = db_query("SELECT * FROM {users}");
$csvdata = 'Uid,Username,Email' . PHP_EOL;
foreach ($results as $record) {
   $row = array();
   $row[] = $record->uid; 
   $row[] = $record->name; 
   $row[] = $record->mail; 
   $csvdata .= implode(',', $row) . PHP_EOL;
}
print $csvdata;
drupal_exit();