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' => array($this, 'cleanValue'),   // for 
37                 'color' => 'yellow', // set color for the cell which is a header element
38                 'fillBlank' => 'gray', // set the color for the cell which is a blank area
39             ),
40             //..... and ther rows...
41     ),
42     
43     // if this is set then it will add a tab foreach one.
44     'workbooks' = array(
45             workbook => '....' // ???
46     ),
47     'leave_open' => false,  // if you call addrows?? later..
48             
49 ));
50
51     callbacks: renderer
52         
53         function($value, $worksheet, $row, $col, $row_data)
54         
55         // callbacks : txtrenderer
56         function($value, $worksheet, $row, $col, $row_data)
57                         
58             
59             
60  */
61  
62  
63  
64 require_once 'Pman.php';
65
66
67 class Pman_Core_SimpleExcel extends Pman
68 {
69     
70     var $worksheet_cfg = array();
71     var $start_row = 0;
72     var $formats = array();
73     var $workbook = false;
74     var $worksheet= false;
75     
76     function Pman_Core_SimpleExcel($data,$cfg)
77     {
78       // print_r($cfg);exit;
79         require_once 'Spreadsheet/Excel/Writer.php';
80         // Creating a workbook
81         $outfile2 = $this->tempName('xls');
82        // var_dump($outfile2);
83         $workbook = new Spreadsheet_Excel_Writer($outfile2);
84         //$workbook = new Spreadsheet_Excel_Writer();
85         $workbook->setVersion(8);
86         // sending HTTP headers
87         $this->workbook = $workbook;
88             
89         $formats = array();
90        
91         $cfg['formats'] = isset($cfg['formats']) ? $cfg['formats'] : array();
92         
93         foreach($cfg['formats'] as $f=>$fcfg) {
94             
95             $this->formats[$f] = & $workbook->addFormat();
96             foreach((array)$fcfg as $k=>$v) {
97                  $this->formats[$f]->{'set' . $k}($v);
98             }
99             
100         }
101          
102          
103         if (!empty($cfg['workbook'])) {
104             $this->buildPage(  array(), $data,$cfg);
105         } elseif (!empty($cfg['workbooks'])) {
106             foreach($cfg['workbooks'] as $i =>$wcfg) {
107                 $this->buildPage(   array() , $data[$i],$wcfg);
108             }
109             
110         }
111         // if workbooks == false - > the user can call buildpage..
112         
113         
114         if (!empty($cfg['leave_open'])) {
115             $this->outfile2 = $outfile2;
116             return;
117         }
118         
119         $workbook->close();
120         $this->outfile2 = $outfile2;
121          
122     }
123     
124     
125     
126     
127     static function date($str)
128     {
129         
130         return (strtotime($str . ' UTC') +  (86400 *  25569)) / 86400;
131         
132     }
133     
134     
135     function buildPage( $formats , $data, $cfg)
136     {
137         $workbook = $this->workbook;
138         //echo '<PRE>';        print_R($cfg);
139       //  print_r($cfg);exit;
140         // Creating a worksheet
141         //print_R($cfg);exit;
142         // copy the config and alias so that book can be written to..
143         $this->worksheet_cfg[$cfg['workbook']] = &$cfg;
144         
145         
146         //$this->formats = (array)$formats;
147         
148         foreach($formats as $k=>$fcfg) {
149             if (!isset($this->formats[$f])) {
150                 $this->formats[$f] = & $workbook->addFormat();
151             }
152             if (is_a($fcfg,'Spreadsheet_Excel_Writer_Format')) {
153                 continue; // skip!?!?
154             }
155             // not an object..
156             foreach((array)$fcfg as $k=>$v) {
157                 $this->formats[$f]->{'set' . $k}($v);
158             }
159         }
160         
161         if (isset($cfg['formats'])) {
162             
163             foreach($cfg['formats'] as $f=>$fcfg) {
164                 if (!isset($this->formats[$f])) {
165                     $this->formats[$f] = & $workbook->addFormat();
166                 }
167                 foreach((array)$fcfg as $k=>$v) {
168                     $this->formats[$f]->{'set' . $k}($v);
169                 }
170                  
171             }
172             
173              
174         }
175         
176         
177         
178         //var_dump($cfg['workbook']);
179
180         $worksheet =  $workbook->addWorksheet($cfg['workbook']);
181         if (is_a($worksheet, 'PEAR_Error')) {
182             die($worksheet->toString());
183         }
184         //print_R($worksheet);
185         $worksheet->setInputEncoding('UTF-8'); 
186          
187         if(!empty($cfg['merged_ranges'])){ // merge cell
188             $worksheet->_merged_ranges = $cfg['merged_ranges'];
189         }
190         
191         $this->worksheet = $worksheet;
192          
193         $start_row = 0;
194         
195         if (!empty($cfg['head'])) {
196             foreach($cfg['head'] as $row) { 
197                 foreach($row as $c => $col) {
198                     if (is_array($col)) {
199                         $format = isset($this->formats[$col[1]] ) ?$this->formats[$col[1]] : false;
200                         $worksheet->write($start_row, $c, $col[0], $format);
201                         continue;
202                     }
203                     
204                     $worksheet->write($start_row, $c, $col);
205                     
206                 }
207                 $start_row++;
208             }
209             // add a spacer..
210             if(!isset($cfg['nonspacer'])){ $start_row++; }
211         }
212             
213                
214         foreach($cfg['cols'] as $c=>$col_cfg) {
215             if (is_string($col_cfg)) {
216                 $cfg['cols'][$c] = array(
217                     'header' => $col_cfg,
218                     'dataIndex' => $col_cfg,
219                     'width' => 50,
220                 );
221             }
222         }
223          
224          
225         foreach($cfg['cols'] as $c=>$col_cfg) {
226             
227             $format = isset($col_cfg['color']) && isset($this->formats[$col_cfg['color']]) ? $this->formats[$col_cfg['color']] : false;
228             $worksheet->write($start_row, $c, @$col_cfg['header'],$format);
229             $worksheet->setColumn ( $c, $c, $col_cfg['width'] / 5);
230         }
231         $start_row++;
232         $this->start_row = &$start_row;
233         
234         
235         $hasRender  = false;
236          
237         if (empty($data)) {
238             return;
239         }
240         
241         
242         foreach($data as $r=>$clo) {
243             $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
244             $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
245              
246         }
247         /// call user render on any that are defined..
248         if ($hasRender) {
249             foreach($data as $r=>$cl) {
250             
251                 foreach($cfg['cols']   as $c=>$col_cfg) {
252                     $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
253                     if (empty($cl[$col_cfg['dataIndex']])) {
254                         continue;
255                     }
256                     if (isset($col_cfg['renderer'])) {
257                         
258                         if (is_a($col_cfg['renderer'], 'Closure')) {
259                             $col_cfg['renderer']->call($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
260                         } else {
261                         // not sure if row is correct here...!!!?
262                             call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
263                         }
264                         
265                     }
266                   //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
267              
268                 }
269             }
270         }
271         $start_row += count($data);
272         
273         if (!empty($cfg['foot'])) {
274             foreach($cfg['foot'] as $row) { 
275                 foreach($row as $c => $col) {
276                     // if it's an array? - formated ???
277                     if (is_array($col)) {
278                         $format = isset($this->formats[$col[1]] ) ? $this->formats[$col[1]] : false;
279                         $worksheet->write($start_row, $c, $col[0], $format);
280                         continue;
281                     }
282                     $worksheet->write($start_row, $c, $col);
283                     
284                 }
285                 $start_row++;
286             }
287             // add a spacer..
288             $start_row++;
289         }
290          
291     }
292     
293     function addLine($worksheet_name, $clo)
294     {
295         $cfg        = $this->worksheet_cfg[$worksheet_name];
296         $start_row  = $this->start_row;
297         $formats    = (array)$this->formats;
298         $worksheet  = $this->worksheet;
299         
300         $hasRender   = false;
301         $r = 0;
302        
303         $cl = $clo;
304         if (is_object($clo)) {
305             $cl = (array)$clo; // lossless converstion..
306         }
307         
308         if (isset($cfg['row_height'])) {
309             $worksheet->setRow($start_row +$r, $cfg['row_height']);
310         }
311         
312         $line_height = (isset($cfg['line_height'])) ? $cfg['line_height'] : 12;
313         $height = 0;
314         
315         foreach($cfg['cols']  as $c => $col_cfg) {
316             
317             if(isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])){
318                 $v =    $cl[$col_cfg['dataIndex']]  ;
319                 
320             }else{
321                 if(isset($col_cfg['fillBlank'])){
322                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
323                 }
324                 continue;
325             }
326             
327             if (!isset($cl[$col_cfg['dataIndex']])) {
328                 continue;
329             }
330             if (isset($col_cfg['txtrenderer'])) {
331                 
332                  if (is_a($col_cfg['txtrenderer'], 'Closure')) {
333                     $v =     $col_cfg['txtrenderer']->call($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
334                 } else {
335                     $v = call_user_func($col_cfg['txtrenderer'], 
336                             $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
337                 }
338                 if ($v === false) {
339                     continue;
340                 }
341               //  var_dump($v);
342             }
343             if (isset($col_cfg['renderer'])) {
344                 $hasRender = true;
345                 continue;
346             }
347             
348             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
349             
350             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
351               
352             
353             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
354           //  print_R(array($start_row+$r, $c, $v, $format));exit;
355           // handle 0 prefixes..
356             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.') 
357                     || 
358                     $dataFormat == 'string' ) {
359                 $worksheet->writeString($start_row+$r, $c, $v, $format);
360             } else {
361           
362                 $worksheet->write($start_row+$r, $c, $v, $format);
363             }
364             
365             if(isset($col_cfg['autoHeight'])){
366                 $vv = explode("\n", $v);
367                 $height = MAX(count($vv) * $line_height, $height);;
368                 $worksheet->setRow($start_row+$r, $height);
369             }
370         }
371         $this->start_row++;
372         
373         return $hasRender;
374     }
375      
376     
377     function send($fname)
378     {
379         if (!empty($this->workbook)) {
380             $this->workbook->close();
381             $this->workbook = false;
382         }
383         
384         require_once 'File/Convert.php';
385         //var_Dump($this->outfile2);
386         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
387         $fn = $fc->convert("application/vnd.ms-excel");
388         //print_r($fc);
389         $fc->serve('attachment',$fname); // can fix IE Mess
390     }
391      
392     
393 }