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     var $postRender = array();
78      
79     function __construct($data,$cfg)
80     {
81       // print_r($cfg);exit;
82         require_once 'Spreadsheet/Excel/Writer.php';
83         // Creating a workbook
84         $outfile2 = $this->tempName('xls');
85        // var_dump($outfile2);
86         $workbook = new Spreadsheet_Excel_Writer($outfile2);
87         //$workbook = new Spreadsheet_Excel_Writer();
88         $workbook->setVersion(8);
89         // sending HTTP headers
90         $this->workbook = $workbook;
91             
92         $formats = array();
93        
94         $cfg['formats'] = isset($cfg['formats']) ? $cfg['formats'] : array();
95         
96         $this->formats['_default_date_format_'] = $workbook->addFormat();;
97         $this->formats['_default_date_format_']->setNumFormat('YYYY-MM-DD');
98         
99         foreach($cfg['formats'] as $f=>$fcfg) {
100             
101             $this->formats[$f] = & $workbook->addFormat();
102             foreach((array)$fcfg as $k=>$v) {
103                 $this->formats[$f]->{'set' . $k}($v);
104             }
105             
106         }
107          
108          
109         if (!empty($cfg['workbook'])) {
110             $this->buildPage(  array(), $data,$cfg);
111         } elseif (!empty($cfg['workbooks'])) {
112             foreach($cfg['workbooks'] as $i =>$wcfg) {
113                 $this->buildPage(   array() , $data[$i],$wcfg);
114             }
115             
116         }
117         // if workbooks == false - > the user can call buildpage..
118         
119         
120         if (!empty($cfg['leave_open'])) {
121             $this->outfile2 = $outfile2;
122             return;
123         }
124         
125         $workbook->close();
126         $this->outfile2 = $outfile2;
127          
128     }
129     
130     
131     
132     
133     static function date($str)
134     {
135         
136         return (strtotime($str . ' UTC') +  (86400 *  25569)) / 86400;
137         
138     }
139     
140     
141     function buildPage( $formats , $data, $cfg)
142     {
143         $workbook = $this->workbook;
144         //echo '<PRE>';        print_R($cfg);
145       //  print_r($cfg);exit;
146         // Creating a worksheet
147         //print_R($cfg);exit;
148         // copy the config and alias so that book can be written to..
149         $this->worksheet_cfg[$cfg['workbook']] = &$cfg;
150         
151         
152         //$this->formats = (array)$formats;
153         
154         foreach($formats as $k=>$fcfg) {
155             if (!isset($this->formats[$f])) {
156                 $this->formats[$f] = & $workbook->addFormat();
157             }
158             if (is_a($fcfg,'Spreadsheet_Excel_Writer_Format')) {
159                 continue; // skip!?!?
160             }
161             // not an object..
162             foreach((array)$fcfg as $k=>$v) {
163                 $this->formats[$f]->{'set' . $k}($v);
164             }
165         }
166         
167         if (isset($cfg['formats'])) {
168             
169             foreach($cfg['formats'] as $f=>$fcfg) {
170                 if (!isset($this->formats[$f])) {
171                     $this->formats[$f] = & $workbook->addFormat();
172                 }
173                 foreach((array)$fcfg as $k=>$v) {
174                     $this->formats[$f]->{'set' . $k}($v);
175                 }
176                  
177             }
178             
179              
180         }
181         
182         
183         
184         //var_dump($cfg['workbook']);
185
186         $worksheet =  $workbook->addWorksheet($cfg['workbook']);
187         if (is_a($worksheet, 'PEAR_Error')) {
188             die($worksheet->toString());
189         }
190         //print_R($worksheet);
191         $worksheet->setInputEncoding('UTF-8'); 
192          
193         if(!empty($cfg['merged_ranges'])){ // merge cell
194             $worksheet->_merged_ranges = $cfg['merged_ranges'];
195         }
196         
197         $this->worksheet = $worksheet;
198          
199         $start_row = 0;
200         
201         if (!empty($cfg['head'])) {
202             foreach($cfg['head'] as $row) { 
203                 foreach($row as $c => $col) {
204                     if (is_array($col)) {
205                         $format = isset($this->formats[$col[1]] ) ?$this->formats[$col[1]] : false;
206                         $worksheet->write($start_row, $c, $col[0], $format);
207                         continue;
208                     }
209                     
210                     $worksheet->write($start_row, $c, $col);
211                     
212                 }
213                 $start_row++;
214             }
215             // add a spacer..
216             if(!isset($cfg['nonspacer'])){ $start_row++; }
217         }
218             
219                
220         foreach($cfg['cols'] as $c=>$col_cfg) {
221             if (is_string($col_cfg)) {
222                 $cfg['cols'][$c] = array(
223                     'header' => $col_cfg,
224                     'dataIndex' => $col_cfg,
225                     'width' => 50,
226                 );
227             }
228         }
229          
230          
231         foreach($cfg['cols'] as $c=>$col_cfg) {
232             
233             $format = isset($col_cfg['color']) && isset($this->formats[$col_cfg['color']]) ? $this->formats[$col_cfg['color']] : false;
234             $worksheet->write($start_row, $c, @$col_cfg['header'],$format);
235             $worksheet->setColumn ( $c, $c, $col_cfg['width'] / 5);
236         }
237         $start_row++;
238         $this->start_row = &$start_row;
239         
240         
241         $hasRender  = false;
242          
243         if (empty($data)) {
244             return;
245         }
246          
247         foreach($cfg['cols']  as $c => $col_cfg) {
248             if (isset($col_cfg['renderer'])) {
249                 $hasRender = true;
250                 break;
251             }
252         }
253         
254         
255         
256         if (is_object($data)) {
257             $data_ar = array();
258             $count = $data->count();
259             $data->find();
260             
261             while($data->fetch()) {
262                 $hasRenderRow = $this->addLine($cfg['workbook'], $data);
263                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
264             }
265             $start_row += $count;
266         } else { 
267         
268             foreach($data as $r=>$clo) {
269                 $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
270                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
271                  
272             }
273         /// call user render on any that are defined..
274             if ($hasRender) {
275                 foreach($data as $r=>$cl) {
276                 
277                     foreach($cfg['cols']   as $c=>$col_cfg) {
278                         $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
279                         if (empty($cl[$col_cfg['dataIndex']])) {
280                             continue;
281                         }
282                         if (!empty($col_cfg['renderer'])) {
283                              if (is_a($col_cfg['renderer'], 'Closure')) {
284                                 $col_cfg['renderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
285                             } else {
286                             // not sure if row is correct here...!!!?
287                                 call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
288                             }
289                             
290                         }
291                       //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
292                  
293                     }
294                 }
295             }
296             $start_row += count($data);
297
298         }
299         
300         if (!empty($cfg['foot'])) {
301             foreach($cfg['foot'] as $row) { 
302                 foreach($row as $c => $col) {
303                     // if it's an array? - formated ???
304                     if (is_array($col)) {
305                         $format = isset($this->formats[$col[1]] ) ? $this->formats[$col[1]] : false;
306                         $worksheet->write($start_row, $c, $col[0], $format);
307                         continue;
308                     }
309                     $worksheet->write($start_row, $c, $col);
310                     
311                 }
312                 $start_row++;
313             }
314             // add a spacer..
315             $start_row++;
316         }
317          
318     }
319     
320     function addLine($worksheet_name, $clo)
321     {
322         $cfg        = $this->worksheet_cfg[$worksheet_name];
323         $start_row  = $this->start_row;
324         $formats    = (array)$this->formats;
325         $worksheet  = $this->worksheet;
326         
327         $hasRender   = false;
328         $r = 0;
329        
330         $cl = $clo;
331         if (is_object($clo)) {
332             $cl = (array)$clo; // lossless converstion..
333         }
334         
335         if (isset($cfg['row_height'])) {
336             $worksheet->setRow($start_row +$r, $cfg['row_height']);
337         }
338         
339         $line_height = (isset($cfg['line_height'])) ? $cfg['line_height'] : 12;
340         $height = 0;
341         
342         foreach($cfg['cols']  as $c => $col_cfg) {
343             
344             if(isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])){
345                 $v =    $cl[$col_cfg['dataIndex']]  ;
346                 
347             }else{
348                 if(isset($col_cfg['fillBlank'])){
349                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
350                 }
351                 continue;
352             }
353             
354             if (!isset($cl[$col_cfg['dataIndex']])) {
355                 continue;
356             }
357             if (isset($col_cfg['txtrenderer'])) {
358                 
359                  if (is_a($col_cfg['txtrenderer'], 'Closure')) {
360                      
361                     $v =     $col_cfg['txtrenderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
362                 } else {
363                     $v = call_user_func($col_cfg['txtrenderer'], 
364                             $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
365                 }
366                 if ($v === false) {
367                     continue;
368                 }
369               //  var_dump($v);
370             }
371             if (isset($col_cfg['renderer'])) {
372                 $hasRender = true;
373                 
374                 $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
375                 if (empty($cl[$col_cfg['dataIndex']])) {
376                     continue;
377                 }
378                 $this->postRender[] = array(
379                     $col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $start_row+$r+1, $c, $cl
380                 );
381                   
382                 
383                 
384                 
385                 continue;
386             }
387             
388             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
389             
390             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
391               
392             
393             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
394           //  print_R(array($start_row+$r, $c, $v, $format));exit;
395           // handle 0 prefixes..
396           
397             if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $v)) {
398                 $dataFormat = 'date';
399                 $format = empty($format) ? $this->formats['_default_date_format_']: $format;
400                 $ut_to_ed_diff = 86400 * 25569;
401                 $gmt = strtotime('1970-01-01');
402
403                 $v = (strtotime($v) + $ut_to_ed_diff - $gmt) / 86400;
404                 // need to +8hrs to get real time..
405                 
406                 
407             }
408           
409             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.' )
410                     || 
411                     $dataFormat == 'string' ) {
412                 $worksheet->writeString($start_row+$r, $c, $v, $format);
413             } else {
414           
415                 $worksheet->write($start_row+$r, $c, $v, $format);
416             }
417             
418             if(isset($col_cfg['autoHeight'])){
419                 $vv = explode("\n", $v);
420                 $height = MAX(count($vv) * $line_height, $height);;
421                 $worksheet->setRow($start_row+$r, $height);
422             }
423         }
424         $this->start_row++;
425         
426         return $hasRender;
427     }
428      
429     
430     function send($fname)
431     {
432         
433         if (!empty($this->postRender)) {
434             foreach($this->postRender as $ar) {
435                  if (is_a($ar[0], 'Closure')) {
436                     $ar[0]($ar[1], $ar[2], $ar[3], $ar[4], $ar[5]);
437                 } else {
438                 // not sure if row is correct here...!!!?
439                     call_user_func($ar[0],$ar[1], $ar[2], $ar[3], $ar[4], $ar[5]);
440                 }
441             }
442             
443         }
444         
445         
446         if (!empty($this->workbook)) {
447             $this->workbook->close();
448             $this->workbook = false;
449         }
450         
451         require_once 'File/Convert.php';
452         //var_Dump($this->outfile2);
453         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
454         $fn = $fc->convert("application/vnd.ms-excel");
455         //print_r($fc);
456         $fc->serve('attachment',$fname); // can fix IE Mess
457     }
458      
459     
460 }