Hello,
I would like to have the ability to export to Excel a gridview. I’m focusing in the Yii part as I already have a view that renders the models to Excel.
I already have a first version that is capable of writing a simple yii gridview maintaining the order and filters in Excel. But having a gridview with a relation, I would like to have some tips or directions to export all columns defined.
For the purpose of this test I have two related models: Employee and Country.
The grid I have is:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'birth_date',
'nif',
[
'class' => DataColumn::className(),
'attribute' => 'countryName',
'format' => 'html',
'value' => function($model, $index, $column) {
$country = Country::find($model->country_id);
return $country ? Html::a($country->nm_country, array('country/update', 'id'=>$model->country_id)) : 'Unknown';
},
'label' => 'Country',
],
['class' => 'yii\grid\ActionColumn',
'contentOptions' => [ 'nowrap' => 'nowrap']
],
],
]);
As this is a temporary test I altered ActionColumn.php (should have extended) and added the following line of code to the end.
protected function renderHeaderCellContent()
{
$querystr = $_SERVER['QUERY_STRING'] == null ? '' : '?'.$_SERVER['QUERY_STRING'];
return html::tag('a','xls',['href' => 'excel'.$querystr])
;
}
This is to send the EmployeeSearch data that is currently selected to the excel action of the Employee Controller:
public function actionExcel()
{
$searchModel = new EmployeeSearch;
$dataProvider = $searchModel->search($_GET, false);
$this->layout = '$content';
return $this->renderPartial('excel', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
I know this is not the best way, but if you can give any ideas to improve this, I would appreciate it.
Right now i can manage to export to Excel but the main problems are:
-
Dataprovider is being setup only with the options sent with ExployeeSearch Model, which doesn’t take into account the columns defined (how to send this?).
-
What is the best way to integrate this into the widget? (where should I send this to? which view should render this?)
I’m fairly new to Yii, so this was a good way to explore but now I’m a little bit stuck.
Thanks in advance.
Pedro