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