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