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