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