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