forked from nkostadinov/EExcelView
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEExcelView.php
276 lines (249 loc) · 8.58 KB
/
EExcelView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
Yii::import('zii.widgets.grid.CGridView');
/**
* @author Nikola Kostadinov
* @license MIT License
* @version 0.3
*/
class EExcelView extends CGridView
{
//Document properties
public $creator = 'Nikola Kostadinov';
public $title = null;
public $subject = 'Subject';
public $description = '';
public $category = '';
public $sheetTitle = 'Sheet1';
//the PHPExcel object
public $objPHPExcel = null;
public $libPath = 'ext.phpexcel.Classes.PHPExcel'; //the path to the PHP excel lib
//config
public $autoWidth = true;
public $exportType = 'Excel5';
public $disablePaging = true;
public $filename = null; //export FileName
public $stream = true; //stream to browser
public $grid_mode = 'grid'; //Whether to display grid ot export it to selected format. Possible values(grid, export)
public $grid_mode_var = 'grid_mode'; //GET var for the grid mode
//buttons config
public $exportButtonsCSS = 'summary';
public $exportButtons = array('Excel2007');
public $exportText = 'Export to: ';
//callbacks
public $onRenderHeaderCell = null;
public $onRenderDataCell = null;
public $onRenderFooterCell = null;
//mime types used for streaming
public $mimeTypes = array(
'Excel5' => array(
'Content-type'=>'application/vnd.ms-excel',
'extension'=>'xls',
'caption'=>'Excel(*.xls)',
),
'Excel2007' => array(
'Content-type'=>'application/vnd.ms-excel',
'extension'=>'xlsx',
'caption'=>'Excel(*.xlsx)',
),
'PDF' =>array(
'Content-type'=>'application/pdf',
'extension'=>'pdf',
'caption'=>'PDF(*.pdf)',
),
'HTML' =>array(
'Content-type'=>'text/html',
'extension'=>'html',
'caption'=>'HTML(*.html)',
),
'CSV' =>array(
'Content-type'=>'application/csv',
'extension'=>'csv',
'caption'=>'CSV(*.csv)',
)
);
public function init()
{
if(isset($_GET[$this->grid_mode_var]))
$this->grid_mode = $_GET[$this->grid_mode_var];
if(isset($_GET['exportType']))
$this->exportType = $_GET['exportType'];
$lib = Yii::getPathOfAlias($this->libPath).'.php';
if($this->grid_mode == 'export' and !file_exists($lib)) {
$this->grid_mode = 'grid';
Yii::log("PHP Excel lib not found($lib). Export disabled !", CLogger::LEVEL_WARNING, 'EExcelview');
}
if($this->disablePaging) //if needed disable paging to export all data
$this->dataProvider->pagination = false;
if($this->grid_mode == 'export')
{
$this->title = $this->title ? $this->title : Yii::app()->getController()->getPageTitle();
$this->initColumns();
//parent::init();
//Autoload fix
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import($this->libPath, true);
$this->objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase','autoload'));
// Creating a workbook
$this->objPHPExcel->getProperties()->setCreator($this->creator);
$this->objPHPExcel->getProperties()->setTitle($this->title);
$this->objPHPExcel->getProperties()->setSubject($this->subject);
$this->objPHPExcel->getProperties()->setDescription($this->description);
$this->objPHPExcel->getProperties()->setCategory($this->category);
} else
parent::init();
}
public function renderHeader()
{
$a=0;
foreach($this->columns as $column)
{
$a=$a+1;
if($column instanceof CButtonColumn)
$head = $column->header;
elseif($column->header===null && $column->name!==null)
{
if($column->grid->dataProvider instanceof CActiveDataProvider)
$head = $column->grid->dataProvider->model->getAttributeLabel($column->name);
else
$head = $column->name;
} else
$head =trim($column->header)!=='' ? $column->header : $column->grid->blankDisplay;
$cell = $this->objPHPExcel->getActiveSheet()->setCellValue($this->columnName($a)."1" ,$head, true);
if(is_callable($this->onRenderHeaderCell))
call_user_func_array($this->onRenderHeaderCell, array($cell, $head));
}
}
public function renderBody()
{
$data=$this->dataProvider->getData();
$n=count($data);
if($n>0)
{
for($row=0;$row<$n;++$row)
$this->renderRow($row);
}
return $n;
}
public function renderRow($row)
{
$data=$this->dataProvider->getData();
$a=0;
foreach($this->columns as $n=>$column)
{
if($column instanceof CLinkColumn)
{
if($column->labelExpression!==null)
$value=$column->evaluateExpression($column->labelExpression,array('data'=>$data[$row],'row'=>$row));
else
$value=$column->label;
} elseif($column instanceof CButtonColumn)
$value = ""; //Dont know what to do with buttons
elseif($column->value!==null)
$value=$this->evaluateExpression($column->value ,array('data'=>$data[$row]));
elseif($column->name!==null) {
//$value=$data[$row][$column->name];
$value= CHtml::value($data[$row], $column->name);
$value=$value===null ? "" : $column->grid->getFormatter()->format($value,'raw');
}
$a++;
$cell = $this->objPHPExcel->getActiveSheet()->setCellValue($this->columnName($a).($row+2) , strip_tags($value), true);
if(is_callable($this->onRenderDataCell))
call_user_func_array($this->onRenderDataCell, array($cell, $data[$row], $value));
}
}
public function renderFooter($row)
{
$a=0;
foreach($this->columns as $n=>$column)
{
$a=$a+1;
if($column->footer)
{
$footer =trim($column->footer)!=='' ? $column->footer : $column->grid->blankDisplay;
$cell = $this->objPHPExcel->getActiveSheet()->setCellValue($this->columnName($a).($row+2) ,$footer, true);
if(is_callable($this->onRenderFooterCell))
call_user_func_array($this->onRenderFooterCell, array($cell, $footer));
}
}
}
public function run()
{
if($this->grid_mode == 'export')
{
$this->renderHeader();
$row = $this->renderBody();
$this->renderFooter($row);
//set auto width
if($this->autoWidth)
foreach($this->columns as $n=>$column)
$this->objPHPExcel->getActiveSheet()->getColumnDimension($this->columnName($n+1))->setAutoSize(true);
$this->objPHPExcel->getActiveSheet()->setTitle($this->sheetTitle);
//create writer for saving
$objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, $this->exportType);
if(!$this->stream)
$objWriter->save($this->filename);
else //output to browser
{
if(!$this->filename)
$this->filename = $this->title;
$this->cleanOutput();
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-type: '.$this->mimeTypes[$this->exportType]['Content-type']);
header('Content-Disposition: attachment; filename="'.$this->filename.'.'.$this->mimeTypes[$this->exportType]['extension'].'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
ob_start();
Yii::app()->end();
ob_end_clean();
}
} else
parent::run();
}
/**
* Returns the coresponding excel column.(Abdul Rehman from yii forum)
*
* @param int $index
* @return string
*/
public function columnName($index)
{
--$index;
if($index >= 0 && $index < 26)
return chr(ord('A') + $index);
else if ($index > 25)
return ($this->columnName($index / 26)).($this->columnName($index%26 + 1));
else
throw new Exception("Invalid Column # ".($index + 1));
}
public function renderExportButtons()
{
foreach($this->exportButtons as $key=>$button)
{
$item = is_array($button) ? CMap::mergeArray($this->mimeTypes[$key], $button) : $this->mimeTypes[$button];
$type = is_array($button) ? $key : $button;
$url = parse_url(Yii::app()->request->requestUri);
//$content[] = CHtml::link($item['caption'], '?'.$url['query'].'exportType='.$type.'&'.$this->grid_mode_var.'=export');
if (key_exists('query', $url))
$content[] = CHtml::link($item['caption'], '?'.$url['query'].'&exportType='.$type.'&'.$this->grid_mode_var.'=export');
else
$content[] = CHtml::link($item['caption'], '?exportType='.$type.'&'.$this->grid_mode_var.'=export');
}
if($content)
echo CHtml::tag('div', array('class'=>$this->exportButtonsCSS), $this->exportText.implode(', ',$content));
}
/**
* Performs cleaning on mutliple levels.
*
* From le_top @ yiiframework.com
*
*/
private static function cleanOutput()
{
for($level=ob_get_level();$level>0;--$level)
{
@ob_end_clean();
}
}
}