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