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