Pman.Gnumeric.js
[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         foreach($cfg['cols']  as $c => $col_cfg) {
247             if (isset($col_cfg['renderer'])) {
248                 $hasRender = true;
249                 break;
250             }
251         }
252         
253         
254         
255         if (is_object($data)) {
256             $data_ar = array();
257             $count = $data->count();
258             $data->find();
259             
260             while($data->fetch()) {
261                 $hasRenderRow = $this->addLine($cfg['workbook'], $data);
262                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
263             }
264             $start_row += $count;
265         } else { 
266         
267             foreach($data as $r=>$clo) {
268                 $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
269                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
270                  
271             }
272         /// call user render on any that are defined..
273             if ($hasRender) {
274                 foreach($data as $r=>$cl) {
275                 
276                     foreach($cfg['cols']   as $c=>$col_cfg) {
277                         $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
278                         if (empty($cl[$col_cfg['dataIndex']])) {
279                             continue;
280                         }
281                         if (!empty($col_cfg['renderer'])) {
282                             
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                 continue;
374             }
375             
376             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
377             
378             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
379               
380             
381             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
382           //  print_R(array($start_row+$r, $c, $v, $format));exit;
383           // handle 0 prefixes..
384           
385             if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $v)) {
386                 $dataFormat = 'date';
387                 $format = empty($format) ? $this->formats['_default_date_format_']: $format;
388                 $ut_to_ed_diff = 86400 * 25569;
389                 $gmt = strtotime('1970-01-01');
390
391                 $v = (strtotime($v) + $ut_to_ed_diff - $gmt) / 86400;
392                 // need to +8hrs to get real time..
393                 
394                 
395             }
396           
397             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.' )
398                     || 
399                     $dataFormat == 'string' ) {
400                 $worksheet->writeString($start_row+$r, $c, $v, $format);
401             } else {
402           
403                 $worksheet->write($start_row+$r, $c, $v, $format);
404             }
405             
406             if(isset($col_cfg['autoHeight'])){
407                 $vv = explode("\n", $v);
408                 $height = MAX(count($vv) * $line_height, $height);;
409                 $worksheet->setRow($start_row+$r, $height);
410             }
411         }
412         $this->start_row++;
413         
414         return $hasRender;
415     }
416      
417     
418     function send($fname)
419     {
420         if (!empty($this->workbook)) {
421             $this->workbook->close();
422             $this->workbook = false;
423         }
424         
425         require_once 'File/Convert.php';
426         //var_Dump($this->outfile2);
427         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
428         $fn = $fc->convert("application/vnd.ms-excel");
429         //print_r($fc);
430         $fc->serve('attachment',$fname); // can fix IE Mess
431     }
432      
433     
434 }