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