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