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