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