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      
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         print_R($col_cfg);exit;
247         
248         foreach($cfg['cols']  as $c => $col_cfg) {
249             if (isset($col_cfg['renderer'])) {
250                 $hasRender = true;
251                 break;
252             }
253         }
254         
255         
256         
257         if (is_object($data)) {
258             $data_ar = array();
259             $count = $data->count();
260             $data->find();
261             
262             while($data->fetch()) {
263                 $hasRenderRow = $this->addLine($cfg['workbook'], $data);
264                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
265             }
266             $start_row += $count;
267         } else { 
268         
269             foreach($data as $r=>$clo) {
270                 $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
271                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
272                  
273             }
274         /// call user render on any that are defined..
275             if ($hasRender) {
276                 foreach($data as $r=>$cl) {
277                 
278                     foreach($cfg['cols']   as $c=>$col_cfg) {
279                         $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
280                         if (empty($cl[$col_cfg['dataIndex']])) {
281                             continue;
282                         }
283                         if (!empty($col_cfg['renderer'])) {
284                              if (is_a($col_cfg['renderer'], 'Closure')) {
285                                 $col_cfg['renderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
286                             } else {
287                             // not sure if row is correct here...!!!?
288                                 call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
289                             }
290                             
291                         }
292                       //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
293                  
294                     }
295                 }
296             }
297             $start_row += count($data);
298
299         }
300         
301         if (!empty($cfg['foot'])) {
302             foreach($cfg['foot'] as $row) { 
303                 foreach($row as $c => $col) {
304                     // if it's an array? - formated ???
305                     if (is_array($col)) {
306                         $format = isset($this->formats[$col[1]] ) ? $this->formats[$col[1]] : false;
307                         $worksheet->write($start_row, $c, $col[0], $format);
308                         continue;
309                     }
310                     $worksheet->write($start_row, $c, $col);
311                     
312                 }
313                 $start_row++;
314             }
315             // add a spacer..
316             $start_row++;
317         }
318          
319     }
320     
321     function addLine($worksheet_name, $clo)
322     {
323         $cfg        = $this->worksheet_cfg[$worksheet_name];
324         $start_row  = $this->start_row;
325         $formats    = (array)$this->formats;
326         $worksheet  = $this->worksheet;
327         
328         $hasRender   = false;
329         $r = 0;
330        
331         $cl = $clo;
332         if (is_object($clo)) {
333             $cl = (array)$clo; // lossless converstion..
334         }
335         
336         if (isset($cfg['row_height'])) {
337             $worksheet->setRow($start_row +$r, $cfg['row_height']);
338         }
339         
340         $line_height = (isset($cfg['line_height'])) ? $cfg['line_height'] : 12;
341         $height = 0;
342         
343         foreach($cfg['cols']  as $c => $col_cfg) {
344             
345             if(isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])){
346                 $v =    $cl[$col_cfg['dataIndex']]  ;
347                 
348             }else{
349                 if(isset($col_cfg['fillBlank'])){
350                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
351                 }
352                 continue;
353             }
354             
355             if (!isset($cl[$col_cfg['dataIndex']])) {
356                 continue;
357             }
358             if (isset($col_cfg['txtrenderer'])) {
359                 
360                  if (is_a($col_cfg['txtrenderer'], 'Closure')) {
361                      
362                     $v =     $col_cfg['txtrenderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
363                 } else {
364                     $v = call_user_func($col_cfg['txtrenderer'], 
365                             $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
366                 }
367                 if ($v === false) {
368                     continue;
369                 }
370               //  var_dump($v);
371             }
372             if (isset($col_cfg['renderer'])) {
373                 $hasRender = true;
374                 continue;
375             }
376             
377             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
378             
379             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
380               
381             
382             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
383           //  print_R(array($start_row+$r, $c, $v, $format));exit;
384           // handle 0 prefixes..
385           
386             if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $v)) {
387                 $dataFormat = 'date';
388                 $format = empty($format) ? $this->formats['_default_date_format_']: $format;
389                 $ut_to_ed_diff = 86400 * 25569;
390                 $gmt = strtotime('1970-01-01');
391
392                 $v = (strtotime($v) + $ut_to_ed_diff - $gmt) / 86400;
393                 // need to +8hrs to get real time..
394                 
395                 
396             }
397           
398             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.' )
399                     || 
400                     $dataFormat == 'string' ) {
401                 $worksheet->writeString($start_row+$r, $c, $v, $format);
402             } else {
403           
404                 $worksheet->write($start_row+$r, $c, $v, $format);
405             }
406             
407             if(isset($col_cfg['autoHeight'])){
408                 $vv = explode("\n", $v);
409                 $height = MAX(count($vv) * $line_height, $height);;
410                 $worksheet->setRow($start_row+$r, $height);
411             }
412         }
413         $this->start_row++;
414         
415         return $hasRender;
416     }
417      
418     
419     function send($fname)
420     {
421         if (!empty($this->workbook)) {
422             $this->workbook->close();
423             $this->workbook = false;
424         }
425         
426         require_once 'File/Convert.php';
427         //var_Dump($this->outfile2);
428         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
429         $fn = $fc->convert("application/vnd.ms-excel");
430         //print_r($fc);
431         $fc->serve('attachment',$fname); // can fix IE Mess
432     }
433      
434     
435 }