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