DataObjects/Core_company_type.php
[Pman.Core] / Pman.Gnumeric.js
1 //<script type="text/javascript">
2 /**
3 * @class Pman Gnumeric.
4 *-> load up a remote xml file of a gnumeric document.
5
6 * -> convert into a usable data structure
7
8 * -> ?? apply templated values ??
9 * -> allow modification of fields
10
11 * -> render to screen.
12
13 * -> send for conversion to XLS (via ssconvert)
14
15 * Usage:
16 <pre><code>
17
18     new Pman.Gnumeric( {
19       url: rootURL + '/xxx/yyy/templates/reports/myreport.xml',
20       data: { ..... },
21       listeners : {
22           load : function()
23           {
24           
25                x.applyData({ ... }); // key value data looks for {value} in strings and replaces it..
26                
27                x.set('A3', 'test');
28                
29                mypanel.update(x.toHTML());
30                
31                x.download()       
32                
33            }
34       }
35     });
36     
37
38 </code></pre>
39
40 * @constructor
41 * @param {Object} cfg   Configuration object.
42 */
43  
44
45
46 Pman.Gnumeric = function (cfg)
47 {
48     cfg.data = cfg.data || {};
49     
50     
51     
52     
53     
54     
55     this.addEvents({
56         /**
57              * @event load
58              * Fires when source document has been loaded
59              * @param {Pman.Gnumerci} this
60              */
61             "load" : true
62     }); 
63     
64     Roo.util.Observable.call(this,cfg);
65     
66     this.defaultCell = {
67         c : 0,
68         r : 0,
69         valueType : 0,
70         valueFormat : '',
71         value : '',
72         colspan: 1,
73         rowspan: 1
74           
75     };
76      
77     this.load();
78     
79    
80     
81     
82 }
83 Roo.extend(Pman.Gnumeric, Roo.util.Observable, {
84     
85     /**
86      * @cfg {String} url the source of the Gnumeric document.
87      */
88     url : false,
89       /**
90      * @cfg {Object} data overlay data for spreadsheet - from constructor.
91      */
92     data : false,
93      /**
94      * @cfg {String} downloadURL where GnumerictoExcel.php is...
95      */
96      
97     downloadURL : false,
98     
99     /**
100      * @type {XmlDocument} doc the gnumeric xml document
101      */
102     doc : false,
103     
104     /**
105      * @type {XmlNode} sheet the 'Sheet' element 
106      */
107     sheet : false,
108     
109     /**
110      * @type {XmlNode} sheet the 'Cells' element 
111      */    
112     cellholder : false,
113     /**
114      * @type {Object} grid the map[row][col] = cellData 
115      */
116     grid : false,
117     /**
118      * @type {Object} colInfo - list of column sizes
119      */
120     colInfo : false,
121     /**
122      * @type {Object} rowInfo - list of row sizes
123      */
124     rowInfo : false,
125     
126     /**
127      * @type {Number} cmax - maximum number of columns
128      */
129     cmax: false,
130     /**
131      * @type {Object} rmax - maximum number of rows
132      */
133     rmax : false,
134        /**
135      * @type {String} stylesheetID id of stylesheet created to render spreadsheat
136      */
137     stylesheetID : false,
138     /**
139      * @type {Number} rowOffset - used by table importer to enable multiple tables to be improted
140      */
141     
142     rowOffset : 0,
143     
144     /**
145      * load:
146      * run the connection, parse document and fire load event..
147      * can be run multiple times with new data..
148      * 
149     */
150     
151     load : function(url)
152     {
153         this.url = url || this.url;
154         if (!this.url) {
155             return;
156         }
157         // reset stufff..
158         this.doc = false;
159         this.sheet = false;
160         this.grid = false;
161         this.colInfo = false;
162         this.rowInfo = false;
163         this.cmax = false;
164         this.rmax = false;
165         
166         if (this.stylesheetID) {
167             
168             Roo.util.CSS.removeStyleSheet(this.stylesheetID);
169             this.stylesheetID = false;
170             
171         }
172         
173         _t = this;
174         var c = new Roo.data.Connection();
175         c.request({
176             url: this.url,
177             method:  'GET',
178             success : function(resp, opts) {
179                 _t.response = resp;
180                 _t.doc = resp.responseXML;
181                 _t.parseDoc();
182                 _t.parseStyles();
183                 _t.overlayStyles();
184                 _t.applyData();
185     
186                 _t.fireEvent('load', _t);
187             },
188             failure : function()
189             {
190                 Roo.MessageBox.alert("Error", "Failed to Load Template for Spreadsheet");
191             }
192         });
193         
194
195     },
196     
197     
198      
199     
200     
201     /**
202      * toRC:
203      * convert 'A1' style position to row/column reference
204      * 
205      * @arg {String} k cell name
206      * @return {Object}  as { r: {Number} , c: {Number}  }
207      */
208     
209     toRC : function(k)
210     {
211           var c = k.charCodeAt(0)-64;
212         var n = k.substring(1);
213         if (k.charCodeAt(1) > 64) {
214             c *=26;
215             c+=k.charCodeAt(1)-64;
216             n = k.substring(2);
217         }
218         return { c:c -1 ,r: (n*1)-1 }
219     },
220       /**
221      * rangeToRC:
222      * convert 'A1:B1' style position to array of row/column references
223      * 
224      * @arg {String} k cell range
225      * @return {Array}  as [ { r: {Number} , c: {Number}  }. { r: {Number} , c: {Number}  } ]
226      */
227     rangeToRC : function(s) {
228         var ar = s.split(':');
229         return [ this.toRC(ar[0]) , this.toRC(ar[1])]
230     },
231     
232     
233     
234    
235     
236     /**
237      * parseDoc:
238      * convert XML document into cells and other data..
239      * 
240      */
241     parseDoc : function() 
242     {
243         var _t = this;
244         this.grid = {}
245         this.rmax = 1;
246         this.cmax = 1;
247         
248         this.sheet = _t.doc.getElementsByTagNameNS('*','Sheet')[0];
249         
250         
251         this.cellholder = this.sheet.getElementsByTagNameNS('*','Cells')[0];
252         var cells = this.sheet.getElementsByTagNameNS('*','Cell');
253
254         
255         
256         Roo.each(cells, function(c) {
257            // Roo.log(c);
258             var row = c.getAttribute('Row') * 1;
259             var col = c.getAttribute('Col') * 1;
260             _t.cmax = Math.max(col+1, _t.cmax);
261             _t.rmax = Math.max(row+1, _t.rmax);
262             var vt = c.getAttribute('ValueType');
263             var vf = c.getAttribute('ValueFormat');
264             var val = c.textContent;
265             
266             if (typeof(_t.grid[row]) == 'undefined') {
267                 _t.grid[row] ={};
268             }
269             _t.grid[row][col] = Roo.applyIf({
270                 valueType : vt,
271                 valueFormat : vf,
272                 value : val,
273                 dom: c,
274                 r: row,
275                 c: col
276             }, _t.defaultCell);
277         });
278        
279         for (var r = 0; r < this.rmax;r++) {
280             if (typeof(this.grid[r]) == 'undefined') {
281               this.grid[r] ={};
282             }
283             for (var c = 0; c < this.cmax;c++) {
284                 if (typeof(this.grid[r][c]) == 'undefined') {
285                     continue;
286                 }
287                 //this.print( "[" + r + "]["+c+"]=" + grid[r][c].value +'<br/>');
288             }
289         }
290         
291         var merge = this.sheet.getElementsByTagNameNS('*','Merge');
292
293         Roo.each(merge, function(c) {
294             var rc = _t.rangeToRC(c.textContent);
295             //Roo.log(JSON.stringify(rc))
296             if (typeof(_t.grid[rc[0].r][rc[0].c]) == 'undefined') {
297                 _t.grid[rc[0].r][rc[0].c] =  Roo.applyIf({ r : rc[0].r, c : rc[0].c }, _t.defaultCell);
298             }
299                 
300             _t.grid[rc[0].r][rc[0].c].colspan = (rc[1].c - rc[0].c) + 1;
301             _t.grid[rc[0].r][rc[0].c].rowspan = (rc[1].r - rc[0].r) + 1;
302             for(var r = (rc[0].r); r < (rc[1].r+1); r++) {
303                for(var c = rc[0].c; c < (rc[1].c+1); c++) {
304                     //Roo.log('adding alias : ' + r+','+c);
305                    _t.grid[r][c] = _t.grid[rc[0].r][rc[0].c];
306                }
307            }
308             
309             
310         });
311         // read colinfo..
312         var ci = this.sheet.getElementsByTagNameNS('*','ColInfo');
313         this.colInfo = {};
314         
315         Roo.each(ci, function(c) {
316             var count = c.getAttribute('Count') || 1;
317             var s =  c.getAttribute('No')*1;
318             for(var i =0; i < count; i++) {
319                 _t.colInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
320             }
321         });
322         
323         
324         ci = this.sheet.getElementsByTagNameNS('*','RowInfo');
325         
326         this.rowInfo = {};
327         Roo.each(ci, function(c) {
328             var count = c.getAttribute('Count') || 1;
329             var s =  c.getAttribute('No')*1;
330             for(var i =0; i < count; i++) {
331                 _t.rowInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
332             }
333         });
334     
335         
336         
337      
338         
339     },
340      /**
341      * overlayStyles:
342      * put the style info onto the cell data.
343      * 
344      */
345     overlayStyles : function ()
346     {
347            // apply styles.
348         var _t = this;
349         Roo.each(this.styles, function(s) {
350        
351             for (var r = s.r; r < s.r1;r++) {
352                 if (typeof(_t.grid[r]) == 'undefined') {
353                    continue;
354                 }
355                 for (var c = s.c; c < s.c1;c++) {
356                     if (c > _t.cmax) continue;
357     
358                     if (typeof(_t.grid[r][c]) == 'undefined') _t.grid[r][c] = Roo.applyIf({ r: r , c : c }, _t.defaultCell);
359                     var g=_t.grid[r][c];
360                     if (typeof(g.cls) =='undefined') {
361                         g.cls = [];
362                         g.styles = [];
363                     }
364                     if (g.cls.indexOf(s.name)  > -1) continue;
365                     g.cls.push(s.name);
366                     g.styles.push(s.dom);
367                     
368                 }
369             }
370         });
371     },
372      /**
373      * parseStyles: 
374      *  read the style information
375      * generates a stylesheet for the current file
376      * this should be disposed of really.....
377      * 
378      */
379     parseStyles : function() {
380                 
381         var srs = this.sheet.getElementsByTagNameNS('*','StyleRegion');
382         var _t  = this;
383         var ent = {};
384         
385         var map =  {
386             HAlign : function(ent,v) { 
387                 ent['text-align'] = { '1' : 'left', '8': 'center', '4' : 'right'}[v] || 'left';
388             },
389             VAlign : function(ent,v) { 
390                 ent['vertical-align'] = { '1' : 'top', '4': 'middel', '8' : 'bottom'}[v]  || 'top'
391             },
392             Fore : function(ent,v) { 
393                 var col=[];
394                 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
395                 ent['color'] = 'rgb(' + col.join(',') + ')';
396             },
397             Back : function(ent,v) { 
398                 var col=[];
399                 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
400                 ent['background-color'] = 'rgb(' + col.join(',') + ')';
401             },
402             FontUnit : function(ent,v) { 
403                 ent['font-size'] = v + 'px';
404             },
405             FontBold : function(ent,v) { 
406                 if (v*1 < 1) return;
407                 ent['font-weight'] = 'bold';
408             },
409             FontItalic : function(ent,v) { 
410                 if (v*0 < 1) return;
411                 //ent['font-weight'] = 'bold';
412             },
413             FontName : function(ent,v) { 
414                 ent['font-family'] = v;
415             },
416             BorderStyle : function(ent,v) { 
417                 var vv  = v.split('-');
418                 ent['border-'+vv[0]+'-style'] = 'solid';
419                 ent['border-'+vv[0]+'-width'] = vv[1]+'px';
420             },
421             BorderColor : function(ent,v) { 
422                 var vv  = v.split('-');
423                 var col=[];
424                 Roo.each(vv[1].split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
425                 ent['border-'+vv[0]+'-color'] = 'rgb(' + col.join(',') + ')';
426             }
427         }
428         function add(e, k, v) {
429             //Roo.log(k,v);
430             e.gstyle[k] = v;
431             if (typeof(map[k]) == 'undefined') {
432                 return;
433             }
434             map[k](e.style,v);    
435         }
436         var css = {};
437         var styles = [];
438         var sid= Roo.id();
439         
440         
441         Roo.each(srs, function(sr,n)
442         {
443             ent = {
444                 c : sr.getAttribute('startCol') *1,
445                 r : sr.getAttribute('startRow')*1,
446                 c1 : (sr.getAttribute('endCol')*1) +1,
447                 r1 : (sr.getAttribute('endRow')*1) +1,
448                 style : {},  // key val of style for HTML..
449                 gstyle : {}, // key val of attributes used..
450                 name : sid +'-gstyle-' + n,
451                 dom : sr
452                 
453             };
454     
455             Roo.each(sr.getElementsByTagNameNS('*','Style')[0].attributes, function(e) { 
456                 add(ent, e.name, e.value);
457             });
458             if (sr.getElementsByTagNameNS('*','Font').length) {
459                 Roo.each(sr.getElementsByTagNameNS('*','Font')[0].attributes, function(e) { 
460                      add(ent, 'Font'+e.name, e.value);
461     
462                 });
463                 add(ent, 'FontName', sr.getElementsByTagNameNS('*','Font')[0].textContent);
464     
465             }
466             if (sr.getElementsByTagNameNS('*','StyleBorder').length) {
467                 Roo.each(sr.getElementsByTagNameNS('*','StyleBorder')[0].childNodes, function(e) {
468                     if (!e.tagName) {
469                         return;
470                     }
471                     Roo.each(e.attributes, function(ea) { 
472                         add(ent, 'Border'+ea.name, e.tagName.split(':')[1].toLowerCase() + '-' + ea.value);
473                     });
474                 })
475                     
476             }
477             styles.push(ent);
478             css['.'+ent.name] = ent.style;
479         });
480         
481         this.styles = styles;
482         
483         this.stylesheetID = sid;
484         Roo.util.CSS.createStyleSheet(css, sid);
485     },
486
487     /* ---------------------------------------  AFTER LOAD METHODS... ----------------------- */
488     /**
489      * set: 
490      * Set the value of a cell..
491      * @param {String} cell name of cell, eg. C10 or { c: 1, r :1 }
492          
493      * @param {Value} value to put in cell..
494      * @param {ValueType} type of value
495      * @param {ValueFormat} value format of cell
496      * 
497      * Cells should exist at present, we do not make them up...
498      */
499      
500     
501     set : function(cell, v, vt, vf) {
502         
503         var cs= typeof(cell) == 'string' ? this.toRC(cell) : cell;
504         //Roo.log( cs.r+ ',' + cs.c + ' = '+ v);
505         // need to generate clell if it doe
506         if (typeof(this.grid[cs.r]) == 'undefined') {
507             Roo.log('no row:' + cell);
508             this.grid[cs.r] = []; // create a row..
509             //return;
510         }
511         if (typeof(this.grid[cs.r][cs.c]) == 'undefined') {
512             Roo.log('cell not defined:' + cell);
513             this.createCell(cs.r,cs.c);
514         }
515         if (typeof(this.grid[cs.r][cs.c].dom) == 'undefined') {
516             Roo.log('no default content for cell:' + cell);
517             this.createCell(cs.r,cs.c);
518             //return;
519         }
520         this.grid[cs.r][cs.c].value=  v;
521         this.grid[cs.r][cs.c].dom.textContent=  v;
522         if (typeof(vt != 'undefined') && vt) {
523             this.grid[cs.r][cs.c].valueType = vt;
524             this.grid[cs.r][cs.c].dom.setAttribute('ValueType', vt);
525         }
526         if (typeof(vf != 'undefined') && vf) {
527             this.grid[cs.r][cs.c].valueFormat = vf;
528             this.grid[cs.r][cs.c].dom.setAttribute('ValueFormat', vf);
529         }
530         
531     },
532     
533     
534     copyRow : function(src, dest) {
535         if (dest == src) {
536             return;
537         }
538        // Roo.log('create Row' + dest);
539         if (typeof(this.grid[dest]) == 'undefined') {
540             this.grid[dest] = {}
541         }
542         
543            
544         for (var c = 0; c < this.cmax; c++) {
545
546             this.copyCell({ r: src, c: c } , { r: dest, c: c});
547             
548         }
549         this.rmax = Math.max(this.rmax, dest +1);
550         
551     },
552     
553     createCell: function(r,c)
554     {
555         //<gnm:Cell Row="6" Col="5" ValueType="60">Updated</gnm:Cell>    
556         var nc = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Cell');
557         this.cellholder.appendChild(nc);
558         var lb = this.doc.createTextNode("\n");// add a line break..
559         this.cellholder.appendChild(lb);
560         
561         nc.setAttribute('Row', new String(r));
562         nc.setAttribute('Col', new String(c));
563         nc.setAttribute('ValueType', '60');
564         nc.textContent = '';
565         
566         this.grid[r][c] = Roo.applyIf({
567             valueType : '60',
568             valueFormat : '',
569             value : '',
570             dom: nc,
571             r: r,
572             c: c
573             }, _t.defaultCell);
574         
575         return nc;
576
577     },
578     
579     
580     copyCell : function(src, dest)
581     {
582         var old = this.grid[src.r][src.c];
583         // is it an alias...
584         if ((old.c != src.c)  || (old.r != src.r)) {
585             // only really works on horizonatal merges..
586             
587             this.grid[dest.r][dest.c] = this.grid[desc.r][old.c]; // let's hope it exists.
588             return;
589         }
590         
591         
592         var nc = Roo.apply({}, this.grid[src.r][src.c]);
593         
594         nc.value = '';
595         if (typeof(old.dom) == 'undefined') {
596             Roo.log("No cell to copy for " + Roo.encode(src));
597             return;
598         }
599         this.grid[dest.r][dest.c] = nc;
600         nc.dom = old.dom.cloneNode(true);
601         nc.dom.setAttribute('Row', dest.r);
602         nc.dom.setAttribute('Cell', dest.c);
603         nc.dom.textContent = '';
604         old.dom.parentNode.appendChild(nc.dom);
605         if (!old.styles || !old.styles.length) {
606             return;
607         }
608         //Roo.log("DEST");
609         //Roo.log(dest);
610         //Roo.log("STYLES");
611         //  .styles...
612         Roo.each(old.styles, function(s) {
613             // try and extend existing styles..
614             var er = s.getAttribute('endRow') * 1;
615             var ec = s.getAttribute('endCol') * 1;
616             //Roo.log(s);
617             if (dest.r == er) {
618                 s.setAttribute('endRow', dest.r + 1);
619             }
620             if (dest.c == ec) {
621                 s.setAttribute('endCol', dest.c + 1);
622             }
623             /*var ns = s.cloneNode(true);
624             s.parentNode.appendChild(ns);
625             ns.setAttribute('startCol', dest.c);
626             ns.setAttribute('startRow', dest.r);
627             ns.setAttribute('endCol', dest.c + 1);
628             ns.setAttribute('endRow', dest.r +1);
629             */
630         });
631         
632     },
633     
634     
635     /**
636      * applyData: 
637      * Set the value of a cell..
638      * @param {String} cell name of cell, eg. C10
639      * @param {Value} value to put in cell..
640      * 
641      * Cells should exist at present, we do not make them up...
642      */
643      
644     applyData : function(data)
645     {
646         
647         data = data || this.data;
648         for (var r = 0; r < this.rmax;r++) {
649             if (typeof(this.grid[r]) == 'undefined') continue;
650             for (var c = 0; c < this.cmax;c++) {  
651                 if (typeof(this.grid[r][c]) == 'undefined') {
652                     continue;
653                 }
654                 if (!this.grid[r][c].value.length 
655                         || !this.grid[r][c].value.match(/\{/)) {
656                     continue;
657                 }
658                 
659                 var x = new Roo.Template({ html: this.grid[r][c].value });
660                 try {
661                     var res = x.applyTemplate(data);
662                     //Roo.log("set " + r  + "," + c + ":"+res)
663                     this.set({ r: r, c: c}, x.applyTemplate(data));
664                 } catch (e) {
665                  //   Roo.log(e.toString());
666                   //  Roo.log(e);
667                     // continue?
668                 }
669                 
670             }
671         }
672             
673     },
674      // now the rows..
675     importTable : function (datagrid, xoff,yoff)
676     {
677         if (!datagrid) {
678             Roo.log("Error table not found!?");
679             return;
680         }
681         xoff = xoff || 0;
682         yoff = yoff || 0;
683         
684         var cleanHTML = function (str) {
685             
686              var ret = str;
687             ret = ret.replace(/&nbsp;/g,'.');
688             ret = ret.replace(/\n/g,'.');
689             ret = ret.replace(/\r/g,'.');
690             var i;
691             while (-1 != (i = ret.indexOf(unescape('%A0')))) {
692                 ret = ret.substring(0,i) + ' ' + ret.substring(i+1,str.length);
693             }
694             return ret;
695         };
696
697         
698         // <cell col="A" row="1">Test< / cell>
699         // <cell col="B" row="2" type="Number" format="test1">30< / cell>
700         var rowOffsets = [];
701         var rows = datagrid.getElementsByTagName('tr');
702         //alert(rows.length);
703         
704         for(var row=0;row<rows.length;row++) {
705             //var style = document.defaultView.getComputedStyle(rows[row], "");
706             
707             //if (rows[row].getAttribute('xls:height')) {
708             //    this.setRowHeight(row+y_offset, 0 + rows[row].getAttribute('xls:height'));
709             //} else {
710             //    this.setRowHeight(row+y_offset, 0 + style.height.replace(/[^0-9.]+/g,''));
711            // }
712             
713             //var coloffset = 0;
714            // if (rowOffsets[row]) {
715            //     coloffset += rowOffsets[row];
716            // }
717             var cols = rows[row].getElementsByTagName('td');
718             
719             
720             for(var col=0;col < cols.length; col++) {
721                 
722                 
723                 //var colat = col + coloffset;
724                 /*
725                 if (cols[col].getAttribute('colspan') && (cols[col].getAttribute('colspan') > 1)) {
726                     
727                     
728                     this.mergeRegion(
729                         colat,
730                         row +y_offset,
731                         colat + (cols[col].getAttribute('colspan') - 1), 
732                         row+y_offset + (
733                                 (cols[col].getAttribute('rowspan') > 1) ?
734                                     (cols[col].getAttribute('rowspan') - 1) : 0
735                                 )
736                     );
737                     
738                     
739                     
740                     coloffset += (cols[col].getAttribute('colspan') - 1);
741                 }
742                
743                 if (cols[col].getAttribute('rowspan') && (cols[col].getAttribute('rowspan') > 1)) {
744                     // this should really do a merge, but it's pretty damn complex...
745                     //this.mergeRegion(colat,row +y_offset,colat + (cols[col].getAttribute('colspan') - 1), row+y_offset);
746                     var rroff = cols[col].getAttribute('colspan')  ? (cols[col].getAttribute('colspan') -0): 1;
747                     var rr = 0;
748                     for (rr = 0; rr < cols[col].getAttribute('rowspan');rr++) {
749                         rowOffsets[rr + row] = col + rroff;
750                     }
751                     
752                 }
753                  */
754                
755                 /*
756                 var style = this.newStyle();
757                 if (style.setFrom(cols[col])) {
758                     style.add(
759                         colat+x_offset,
760                         row+y_offset,
761                         
762                         colat+x_offset + ((cols[col].getAttribute('colspan') > 1) ?
763                                     (cols[col].getAttribute('colspan') - 1) : 0),
764                         row+y_offset  + ((cols[col].getAttribute('rowspan') > 1) ?
765                                     (cols[col].getAttribute('rowspan') - 1) : 0) 
766                     );
767                 }
768                 
769                  */
770                 // skip blank cells
771                 if (!cols[col].childNodes.length) {
772                     continue;
773                 }
774                 
775                 
776                 
777                 
778                 var vt = '60';
779                 var vf = false;
780                 
781                 switch(cols[col].getAttribute('xls:type')) {
782                     case 'int':
783                         vt = 30; // int!!!!
784                         break;
785                         
786                     case 'float':
787                         vt = 40; // float!!!!
788                         if (cols[col].getAttribute('xls:floatformat')) {
789                                 vf = cols[col].getAttribute('xls:floatformat');
790                         }
791                         break;
792                         
793                     case 'date':
794                         vt = 30;
795                         //ValueFormat="d/m/yyyy" 38635  
796                         var vf = 'd/m/yyy';
797                         if (cols[col].getAttribute('xls:dateformat')) {
798                             vf= cols[col].getAttribute('xls:dateformat');
799                         }
800                         
801                        
802                         
803                         break;
804                     
805                     default:
806                        
807                         break;
808                 }
809                 /*
810                 if (cols[col].getAttribute('xls:src')) {
811                     //alert(cols[col].childNodes[0].width);
812                     if (this.writeImage(
813                         row+y_offset, 
814                         colat+x_offset+coloffset, 
815                         cols[col].getAttribute('xls:src'), 
816                         cols[col].childNodes[0].width, 
817                         cols[col].childNodes[0].height
818                         )) {
819                        
820                     }
821                     continue;
822                 }
823                 */
824                  
825                 if (!cols[col].childNodes[0].nodeValue) {
826                     continue;
827                 }
828                 if (!cols[col].childNodes[0].nodeValue.replace(/^\s*|\s*$/g,"").length) {
829                     continue;
830                 }
831                 // strip me.!
832                 var cell_value_text = cleanHTML(cols[col].childNodes[0].nodeValue);
833        
834                 if (cols[col].getAttribute('xls:percent')) {
835                     cell_value_text = '' + ((cell_value_text * 1) / 100);
836                 }
837
838                 if (cell_value_text.length && (vt == 30)) {
839                     var bits = cell_value_text.split(/-/);
840                     var cur = new Date(bits[0],bits[1]-1,bits[2]);
841                     cell_value_text = '' + Math.round((cur.getTime() - Date.UTC(1899,11,30)) / (24 * 60 * 60 * 1000));
842                 }
843
844                 
845                 
846                 if (cols[col].getAttribute('xls:formula')) {
847                     var s = cols[col].getAttribute('xls:formula');
848                     cell.removeAttribute('ValueType');
849                     cell_value_text = s.replace(/#row#/g,(row + y_offset + 1));
850                 }
851                 this.set({ r: row + yoff, c : col + xoff }, cell_value_text, vt, vf);
852                 
853                 
854                 
855                 
856                 
857             }
858         }
859         this.rowOffset += rows.length;
860         
861     },
862     
863
864     
865      /**
866      * toHTML: 
867      * Convert spreadsheet into a HTML table.
868      */
869             
870     toHTML :function()
871     {
872          var _t = this;
873         function calcWidth(sc, span)
874         {
875             var n =0;
876             for(var i =sc; i< sc+span;i++) {
877                 n+=_t.colInfo[i];
878             }   
879             return n;
880         }
881         
882         var grid = this.grid;
883         // lets do a basic dump..
884         var out = '<table style="table-layout:fixed;" cellpadding="0" cellspacing="0">';
885         for (var r = 0; r < this.rmax;r++) {
886             out += '<tr style="height:'+this.rowInfo[r]+'px;">';
887             for (var c = 0; c < this.cmax;c++) {
888                 var g = (typeof(grid[r][c]) == 'undefined') ? defaultCell  : grid[r][c];
889                 
890                 if (typeof(g.cls) =='undefined') g.cls = [];
891                 var w= calcWidth(c,g.colspan);
892                 out+=String.format('<td colspan="{0}" rowspan="{1}"  class="{4}"><div style="{3}">{2}</div></td>', 
893                     g.colspan, g.rowspan, g.value,
894                     'overflow:hidden;' + 
895                     'width:'+w+'px;' +
896                    
897                     'text-overflow:ellipsis;' +
898                     'white-space:nowrap;',
899                      g.cls.join(' ')
900     
901     
902                 );
903                 c+=(g.colspan-1);
904             }
905             out += '</tr>';
906         }
907         //Roo.log(out);
908         return out+'</table>';
909         
910         
911         
912     },
913     /**
914      * download:
915      * @param {String} name  filename to downlaod (without xls)
916      * @param {String} callback  (optional) - callback to call after callback is complete.
917      */
918     download : function(name,callback)
919     {
920         name = name || "Missing_download_filename";
921         
922         if (this.downloadURL && this.downloadURL.charAt(this.downloadURL .length-1) != '/') {
923             this.downloadURL += '/';
924         }
925         
926         var ser = new XMLSerializer();
927         var x = new Pman.Download({
928             method: 'POST',
929             params : {
930                xml : ser.serializeToString(this.doc),
931                format : 'xls', //xml
932                debug : 0
933                
934             },
935             url : (this.downloadURL || (baseURL + '/GnumericToExcel/')) + name + '.xls',
936             success : function() {
937                 Roo.MessageBox.alert("Alert", "File should have downloaded now");
938                 if (callback) {
939                     callback();
940                 }
941             }
942         });
943          
944     }
945
946 });