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