Is there a reason you only want Apex solutions? What is the end goal? Are you wanting a full back up of your org in CSV? There are other options that are very powerful. I would recommend DemandTools (paid) or Jitterbit (free) for CSVs. Or if you are flexible and can use a database back up of your org, CopyStorm from CapStorm.
I think Sandhya actually provided a great link for your specific question. See point #7. It doesn't provide a full solution but gives building blocks.
I would suggest you below blog which has the sample code for the same.
https://douglascayers.com/2016/03/20/salesforce-easy-ways-to-export-data-as-csv/
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
Best Regards
Sandhya
I saw this post. but I want to export all data from Salesforce in CSV format and it should be stored in a folder.
I think Sandhya actually provided a great link for your specific question. See point #7. It doesn't provide a full solution but gives building blocks.