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