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             $formats[$f] = & $workbook->addFormat();
80             foreach((array)$fcfg as $k=>$v) {
81                 $formats[$f]->{'set' . $k}($v);
82             }
83             $this->formats = $formats;
84         }
85          
86          
87         if (!empty($cfg['workbook'])) {
88             $this->buildPage(   $formats , $data,$cfg);
89         } elseif (!empty($cfg['workbooks'])) {
90             foreach($cfg['workbooks'] as $i =>$wcfg) {
91                 $this->buildPage(   $formats , $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         if (isset($cfg['formats']) && empty($formats)) {
133             
134             foreach($cfg['formats'] as $f=>$fcfg) {
135                 if (!isset($this->formats[$f])) {
136                     $this->formats[$f] = & $workbook->addFormat();
137                 }
138                 foreach((array)$fcfg as $k=>$v) {
139                     $this->formats[$f]->{'set' . $k}($v);
140                 }
141                  
142             }
143             
144              
145         }
146         
147         
148         
149         //var_dump($cfg['workbook']);
150
151         $worksheet =  $workbook->addWorksheet($cfg['workbook']);
152         if (is_a($worksheet, 'PEAR_Error')) {
153             die($worksheet->toString());
154         }
155         //print_R($worksheet);
156         $worksheet->setInputEncoding('UTF-8'); 
157          
158         if(!empty($cfg['merged_ranges'])){ // merge cell
159             $worksheet->_merged_ranges = $cfg['merged_ranges'];
160         }
161         
162         $this->worksheet = $worksheet;
163          
164         $start_row = 0;
165         
166         if (!empty($cfg['head'])) {
167             foreach($cfg['head'] as $row) { 
168                 foreach($row as $c => $col) {
169                     if (is_array($col)) {
170                         $format = isset($formats[$col[1]] ) ? $formats[$col[1]] : false;
171                         $worksheet->write($start_row, $c, $col[0], $format);
172                         continue;
173                     }
174                     
175                     $worksheet->write($start_row, $c, $col);
176                     
177                 }
178                 $start_row++;
179             }
180             // add a spacer..
181             if(!isset($cfg['nonspacer'])){ $start_row++; }
182         }
183             
184                
185         foreach($cfg['cols'] as $c=>$col_cfg) {
186             if (is_string($col_cfg)) {
187                 $cfg['cols'][$c] = array(
188                     'header' => $col_cfg,
189                     'dataIndex' => $col_cfg,
190                     'width' => 50,
191                 );
192             }
193         }
194          
195          
196         foreach($cfg['cols'] as $c=>$col_cfg) {
197             $format = isset($col_cfg['color']) ? $formats[$col_cfg['color']] : false;
198             $worksheet->write($start_row, $c, $col_cfg['header'],$format);
199             $worksheet->setColumn ( $c, $c, $col_cfg['width'] / 5);
200         }
201         $start_row++;
202         $this->start_row = &$start_row;
203         
204         
205         $hasRender  = false;
206          
207         if (empty($data)) {
208             return;
209         }
210         
211         
212         foreach($data as $r=>$clo) {
213             $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
214             $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
215              
216         }
217         /// call user render on any that are defined..
218         if ($hasRender) {
219             foreach($data as $r=>$cl) {
220             
221                 foreach($cfg['cols']   as $c=>$col_cfg) {
222                     $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
223                     if (empty($cl[$col_cfg['dataIndex']])) {
224                         continue;
225                     }
226                     if (isset($col_cfg['renderer'])) {
227                         // not sure if row is correct here...!!!?
228                         call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
229                         
230                     }
231                   //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
232              
233                 }
234             }
235         }
236         $start_row += count($data);
237         
238         if (!empty($cfg['foot'])) {
239             foreach($cfg['foot'] as $row) { 
240                 foreach($row as $c => $col) {
241                     // if it's an array? - formated ???
242                     if (is_array($col)) {
243                         $format = isset($formats[$col[1]] ) ? $formats[$col[1]] : false;
244                         $worksheet->write($start_row, $c, $col[0], $format);
245                         continue;
246                     }
247                     $worksheet->write($start_row, $c, $col);
248                     
249                 }
250                 $start_row++;
251             }
252             // add a spacer..
253             $start_row++;
254         }
255         
256         
257     }
258     
259     function addLine($worksheet_name, $clo)
260     {
261         $cfg        = $this->worksheet_cfg[$worksheet_name];
262         $start_row  = $this->start_row;
263         $formats    = (array)$this->formats;
264         $worksheet  = $this->worksheet;
265         
266         $hasRender   = false;
267         $r = 0;
268        
269         $cl = $clo;
270         if (is_object($clo)) {
271             $cl = (array)$clo; // lossless converstion..
272         }
273         
274         if (isset($cfg['row_height'])) {
275             $worksheet->setRow($start_row +$r, $cfg['row_height']);
276         }
277         
278         foreach($cfg['cols']  as $c=>$col_cfg) {
279             
280             if(isset($cl[$col_cfg['dataIndex']])){
281                 $v = $cl[$col_cfg['dataIndex']];
282             }else{
283                 if(isset($col_cfg['fillBlank'])){
284                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
285                 }
286                 continue;
287             }
288             
289             if (!isset($cl[$col_cfg['dataIndex']])) {
290                 continue;
291             }
292             if (isset($col_cfg['txtrenderer'])) {
293                 $v = call_user_func($col_cfg['txtrenderer'], 
294                         $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
295                 if ($v === false) {
296                     continue;
297                 }
298               //  var_dump($v);
299             }
300             if (isset($col_cfg['renderer'])) {
301                 $hasRender = true;
302                 continue;
303             }
304             
305             $v = @iconv('UTF-8', 'UTF-8//IGNORE', $v);
306             
307             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
308              ;
309             
310             
311             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
312           //  print_R(array($start_row+$r, $c, $v, $format));exit;
313           // handle 0 prefixes..
314             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.') 
315                     || 
316                     $dataFormat == 'string' ) {
317                 $worksheet->writeString($start_row+$r, $c, $v, $format);
318             } else {
319           
320                 $worksheet->write($start_row+$r, $c, $v, $format);
321             }
322         }
323         $this->start_row++;
324         
325         return $hasRender;
326     }
327      
328     
329     function send($fname)
330     {
331         if (!empty($this->workbook)) {
332             $this->workbook->close();
333             $this->workbook = false;
334         }
335         
336         require_once 'File/Convert.php';
337         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
338         $fn = $fc->convert("application/vnd.ms-excel"); 
339         $fc->serve('attachment',$fname); // can fix IE Mess
340     }
341      
342     
343 }