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