Please read this tutorial before to follow this post.
http://www.bsourcecode.com/2013/04/yii-cactivedataprovider-to-excel/
This tutorial will help you to create a excel sheet using custom sql query.
In Model Code
public function searchbydocumentdetails(){ $query="SELECT * FROM TABLE_NAME"; return new CSqlDataProvider($query, array( 'pagination'=>false ) ); }
In Controller Code
public function customsqltoexcel(){ $document=new Document; $data=$document->searchbydocumentdetails(); $this->toExcel($data, array('DocuemntName', 'CategoryName', 'DownloadCredits', 'UploadCredits', 'Downloadimits', 'Count', 'Status'), 'Document Reports', array( 'creator' => 'Sourcecode', ), 'Excel2007'// This is the default value, so you can omit it. You can export to CSV, PDF or HTML too ); }