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