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