SimpleExcel.php
[Pman.Core] / SimpleExcel.php
1 <?php
2
3 /**
4  * class to generate excel file from rows of data, and a configuration.
5  *
6  * usage :
7  *   $x = new Pman_Core_SimpleExcel($data_array, array())
8  *   $x->send($fn);
9  *
10  * 
11  *
12  
13 new Pman_Core_SimpleExcel($data_array, array(
14     'formats' => array(
15         'format_name' => array( 'Align' =>  'left' ), // etc...
16     ),
17     'workbook' => 'name_of_workbook'm
18     
19     'head' => array(
20         array ( 'this', 'is', 'the' , 'first', 'row'), 
21         array ( 'this', 'is', 'the' , 'seconde', 'row'),  // ... etc.
22         array (  array( 'string', 'format_name') , 'another cell') ,  // with formating..
23     ),
24    
25     'merged_ranges' => array(
26                            array($first_row, $first_col, $last_row, $last_col),
27                          array($first_row, $first_col, $last_row, $last_col),
28     ),
29     'cols' =>  array(
30             array(
31                 'header'=> "Thumbnail",
32                 'dataIndex'=> 'id',
33                 'dataFormat' => 'string' // to force a string..
34                 'width'=>  75,
35                 'renderer' => array($this, 'getThumb'),
36                 'txtrenderer' => function($value, $worksheet, $row, $col, $row_data) {
37                     return $value
38                 },   // for text content...
39                 'color' => 'yellow', // set color for the cell which is a header element
40                 'fillBlank' => 'gray', // set the color for the cell which is a blank area
41             ),
42             //..... and ther rows...
43     ),
44     
45     // if this is set then it will add a tab foreach one.
46     'workbooks' = array(
47             workbook => '....' // ???
48     ),
49     'leave_open' => false,  // if you call addrows?? later..
50             
51 ));
52
53     callbacks: renderer
54         
55         function($value, $worksheet, $row, $col, $row_data)
56         
57         // callbacks : txtrenderer
58         function($value, $worksheet, $row, $col, $row_data)
59                         
60             
61             
62  */
63  
64  
65  
66 require_once 'Pman.php';
67
68
69 class Pman_Core_SimpleExcel extends Pman
70 {
71     
72     var $worksheet_cfg = array();
73     var $start_row = 0;
74     var $formats = array();
75     var $workbook = false;
76     var $worksheet= false;
77     
78     function Pman_Core_SimpleExcel($data,$cfg)
79     {
80       // print_r($cfg);exit;
81         require_once 'Spreadsheet/Excel/Writer.php';
82         // Creating a workbook
83         $outfile2 = $this->tempName('xls');
84        // var_dump($outfile2);
85         $workbook = new Spreadsheet_Excel_Writer($outfile2);
86         //$workbook = new Spreadsheet_Excel_Writer();
87         $workbook->setVersion(8);
88         // sending HTTP headers
89         $this->workbook = $workbook;
90             
91         $formats = array();
92        
93         $cfg['formats'] = isset($cfg['formats']) ? $cfg['formats'] : array();
94         
95         foreach($cfg['formats'] as $f=>$fcfg) {
96             
97             $this->formats[$f] = & $workbook->addFormat();
98             foreach((array)$fcfg as $k=>$v) {
99                  $this->formats[$f]->{'set' . $k}($v);
100             }
101             
102         }
103          
104          
105         if (!empty($cfg['workbook'])) {
106             $this->buildPage(  array(), $data,$cfg);
107         } elseif (!empty($cfg['workbooks'])) {
108             foreach($cfg['workbooks'] as $i =>$wcfg) {
109                 $this->buildPage(   array() , $data[$i],$wcfg);
110             }
111             
112         }
113         // if workbooks == false - > the user can call buildpage..
114         
115         
116         if (!empty($cfg['leave_open'])) {
117             $this->outfile2 = $outfile2;
118             return;
119         }
120         
121         $workbook->close();
122         $this->outfile2 = $outfile2;
123          
124     }
125     
126     
127     
128     
129     static function date($str)
130     {
131         
132         return (strtotime($str . ' UTC') +  (86400 *  25569)) / 86400;
133         
134     }
135     
136     
137     function buildPage( $formats , $data, $cfg)
138     {
139         $workbook = $this->workbook;
140         //echo '<PRE>';        print_R($cfg);
141       //  print_r($cfg);exit;
142         // Creating a worksheet
143         //print_R($cfg);exit;
144         // copy the config and alias so that book can be written to..
145         $this->worksheet_cfg[$cfg['workbook']] = &$cfg;
146         
147         
148         //$this->formats = (array)$formats;
149         
150         foreach($formats as $k=>$fcfg) {
151             if (!isset($this->formats[$f])) {
152                 $this->formats[$f] = & $workbook->addFormat();
153             }
154             if (is_a($fcfg,'Spreadsheet_Excel_Writer_Format')) {
155                 continue; // skip!?!?
156             }
157             // not an object..
158             foreach((array)$fcfg as $k=>$v) {
159                 $this->formats[$f]->{'set' . $k}($v);
160             }
161         }
162         
163         if (isset($cfg['formats'])) {
164             
165             foreach($cfg['formats'] as $f=>$fcfg) {
166                 if (!isset($this->formats[$f])) {
167                     $this->formats[$f] = & $workbook->addFormat();
168                 }
169                 foreach((array)$fcfg as $k=>$v) {
170                     $this->formats[$f]->{'set' . $k}($v);
171                 }
172                  
173             }
174             
175              
176         }
177         
178         
179         
180         //var_dump($cfg['workbook']);
181
182         $worksheet =  $workbook->addWorksheet($cfg['workbook']);
183         if (is_a($worksheet, 'PEAR_Error')) {
184             die($worksheet->toString());
185         }
186         //print_R($worksheet);
187         $worksheet->setInputEncoding('UTF-8'); 
188          
189         if(!empty($cfg['merged_ranges'])){ // merge cell
190             $worksheet->_merged_ranges = $cfg['merged_ranges'];
191         }
192         
193         $this->worksheet = $worksheet;
194          
195         $start_row = 0;
196         
197         if (!empty($cfg['head'])) {
198             foreach($cfg['head'] as $row) { 
199                 foreach($row as $c => $col) {
200                     if (is_array($col)) {
201                         $format = isset($this->formats[$col[1]] ) ?$this->formats[$col[1]] : false;
202                         $worksheet->write($start_row, $c, $col[0], $format);
203                         continue;
204                     }
205                     
206                     $worksheet->write($start_row, $c, $col);
207                     
208                 }
209                 $start_row++;
210             }
211             // add a spacer..
212             if(!isset($cfg['nonspacer'])){ $start_row++; }
213         }
214             
215                
216         foreach($cfg['cols'] as $c=>$col_cfg) {
217             if (is_string($col_cfg)) {
218                 $cfg['cols'][$c] = array(
219                     'header' => $col_cfg,
220                     'dataIndex' => $col_cfg,
221                     'width' => 50,
222                 );
223             }
224         }
225          
226          
227         foreach($cfg['cols'] as $c=>$col_cfg) {
228             
229             $format = isset($col_cfg['color']) && isset($this->formats[$col_cfg['color']]) ? $this->formats[$col_cfg['color']] : false;
230             $worksheet->write($start_row, $c, @$col_cfg['header'],$format);
231             $worksheet->setColumn ( $c, $c, $col_cfg['width'] / 5);
232         }
233         $start_row++;
234         $this->start_row = &$start_row;
235         
236         
237         $hasRender  = false;
238          
239         if (empty($data)) {
240             return;
241         }
242         foreach($cfg['cols']  as $c => $col_cfg) {
243             if (isset($col_cfg['renderer'])) {
244                 $hasRender = true;
245                 break;
246             }
247         }
248         
249         
250         
251         if (is_object($data)) {
252             $data_ar = array();
253             $count = $data->count();
254             $data->find();
255             
256             while($data->fetch()) {
257                 $hasRenderRow = $this->addLine($cfg['workbook'], $data);
258                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
259             }
260             $start_row += $count;
261         } else { 
262         
263             foreach($data as $r=>$clo) {
264                 $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
265                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
266                  
267             }
268         /// call user render on any that are defined..
269             if ($hasRender) {
270                 foreach($data as $r=>$cl) {
271                 
272                     foreach($cfg['cols']   as $c=>$col_cfg) {
273                         $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
274                         if (empty($cl[$col_cfg['dataIndex']])) {
275                             continue;
276                         }
277                         if (!empty($col_cfg['renderer'])) {
278                             
279                             if (is_a($col_cfg['renderer'], 'Closure')) {
280                                 $col_cfg['renderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
281                             } else {
282                             // not sure if row is correct here...!!!?
283                                 call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
284                             }
285                             
286                         }
287                       //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
288                  
289                     }
290                 }
291             }
292             $start_row += count($data);
293
294         }
295         
296         if (!empty($cfg['foot'])) {
297             foreach($cfg['foot'] as $row) { 
298                 foreach($row as $c => $col) {
299                     // if it's an array? - formated ???
300                     if (is_array($col)) {
301                         $format = isset($this->formats[$col[1]] ) ? $this->formats[$col[1]] : false;
302                         $worksheet->write($start_row, $c, $col[0], $format);
303                         continue;
304                     }
305                     $worksheet->write($start_row, $c, $col);
306                     
307                 }
308                 $start_row++;
309             }
310             // add a spacer..
311             $start_row++;
312         }
313          
314     }
315     
316     function addLine($worksheet_name, $clo)
317     {
318         $cfg        = $this->worksheet_cfg[$worksheet_name];
319         $start_row  = $this->start_row;
320         $formats    = (array)$this->formats;
321         $worksheet  = $this->worksheet;
322         
323         $hasRender   = false;
324         $r = 0;
325        
326         $cl = $clo;
327         if (is_object($clo)) {
328             $cl = (array)$clo; // lossless converstion..
329         }
330         
331         if (isset($cfg['row_height'])) {
332             $worksheet->setRow($start_row +$r, $cfg['row_height']);
333         }
334         
335         $line_height = (isset($cfg['line_height'])) ? $cfg['line_height'] : 12;
336         $height = 0;
337         
338         foreach($cfg['cols']  as $c => $col_cfg) {
339             
340             if(isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])){
341                 $v =    $cl[$col_cfg['dataIndex']]  ;
342                 
343             }else{
344                 if(isset($col_cfg['fillBlank'])){
345                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
346                 }
347                 continue;
348             }
349             
350             if (!isset($cl[$col_cfg['dataIndex']])) {
351                 continue;
352             }
353             if (isset($col_cfg['txtrenderer'])) {
354                 
355                  if (is_a($col_cfg['txtrenderer'], 'Closure')) {
356                      
357                     $v =     $col_cfg['txtrenderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
358                 } else {
359                     $v = call_user_func($col_cfg['txtrenderer'], 
360                             $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
361                 }
362                 if ($v === false) {
363                     continue;
364                 }
365               //  var_dump($v);
366             }
367             if (isset($col_cfg['renderer'])) {
368                 $hasRender = true;
369                 continue;
370             }
371             
372             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
373             
374             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
375               
376             
377             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
378           //  print_R(array($start_row+$r, $c, $v, $format));exit;
379           // handle 0 prefixes..
380           
381             if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $v)) {
382                 $dataFormat = 'date';
383                 $format = empty($format) ? 'YYYY-MM-DD' : $format;
384                 $ut_to_ed_diff = 86400 * 25569;
385
386                 $v = (strtotime($v) + $ut_to_ed_diff) / 86400;
387             }
388           
389             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.' )
390                     || 
391                     $dataFormat == 'string' ) {
392                 $worksheet->writeString($start_row+$r, $c, $v, $format);
393             } else {
394           
395                 $worksheet->write($start_row+$r, $c, $v, $format);
396             }
397             
398             if(isset($col_cfg['autoHeight'])){
399                 $vv = explode("\n", $v);
400                 $height = MAX(count($vv) * $line_height, $height);;
401                 $worksheet->setRow($start_row+$r, $height);
402             }
403         }
404         $this->start_row++;
405         
406         return $hasRender;
407     }
408      
409     
410     function send($fname)
411     {
412         if (!empty($this->workbook)) {
413             $this->workbook->close();
414             $this->workbook = false;
415         }
416         
417         require_once 'File/Convert.php';
418         //var_Dump($this->outfile2);
419         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
420         $fn = $fc->convert("application/vnd.ms-excel");
421         //print_r($fc);
422         $fc->serve('attachment',$fname); // can fix IE Mess
423     }
424      
425     
426 }