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