= Yii 2 Data Export = == Export to Excel File == //... use yii\filters\AccessControl; use yii\filters\VerbFilter; use yii\helpers\Html; class CustomerController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => [/* ... */ 'export'], 'allow' => true, 'roles' => ['@'], // @ = Authenticated users ], ], ], //... ]; } //... /** * Generated export files containing of all existing Customers. * @param none * @return mixed */ public function actionExport($type='csv') { $models = Customer::find()->All(); switch($type) { case 'excel': //-------------------- // Excel Export //-------------------- $filename = 'Customer-Data-'.Date('YmdGis').".xls"; header("Content-type: application/vnd-ms-excel"); header("Content-Disposition: attachment; filename=".$filename); echo ''; foreach($models as $row){ echo ' '; } echo '
account_number contact company_name address1 address2 city state_prov postal_code country phone phone_ext email website ship_address_id notes status
'.$row['account_number'] .' '.$row['contact'] .' '.$row['company_name'] .' '.$row['address1'] .' '.$row['address2'] .' '.$row['city'] .' '.$row['state_prov'] .' '.$row['postal_code'] .' '.$row['country'] .' '.$row['phone'] .' '.$row['phone_ext'] .' '.$row['email'] .' '.$row['website'] .' '.$row['ship_address_id'] .' '.$row['notes'] .' '.$row['status'] .'
'; break; case 'csv': default: //-------------------- // CSV Export //-------------------- $filename = 'Customer-Data-'.Date('YmdGis').".csv"; header("Content-type: text/csv"); $extension = 'csv'; header("Content-Disposition: attachment; filename=".$filename); // header row $data = implode("\t", [ 'account_number', 'contact', 'company_name', 'address1', 'address2', 'city', 'state_prov', 'postal_code', 'country', 'phone', 'phone_ext', 'email', 'website', 'ship_address_id', 'notes', 'status' ]) . "\n"; // data row foreach($models as $row) { $data .= implode("\t", [ $row['account_number'] , $row['contact'] , $row['company_name'] , $row['address1'] , $row['address2'] , $row['city'] , $row['state_prov'] , $row['postal_code'] , $row['country'] , $row['phone'] , $row['phone_ext'] , $row['email'] , $row['website'] , $row['ship_address_id'] , str_replace("\r\n", "|", Html::encode($row['notes'])), $row['status'] , ]) . "\n"; } // return data results echo $data; break; } } }