Pman.Gnumeric.js
[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} colInfoDom - column sizes dom element
123      */
124     colInfoDom : false,
125     /**
126      * @type {Object} rowInfo - list of row sizes
127      */
128     rowInfo : false,
129      /**
130      * @type {Object} rowInfoDom - dom elements with sizes
131      */
132     rowInfoDom : false,
133     /**
134      * @type {Number} cmax - maximum number of columns
135      */
136     cmax: false,
137     /**
138      * @type {Object} rmax - maximum number of rows
139      */
140     rmax : false,
141        /**
142      * @type {String} stylesheetID id of stylesheet created to render spreadsheat
143      */
144     stylesheetID : false,
145     /**
146      * @type {Number} rowOffset - used by table importer to enable multiple tables to be improted
147      */
148     
149     rowOffset : 0,
150     
151     /**
152      * load:
153      * run the connection, parse document and fire load event..
154      * can be run multiple times with new data..
155      * 
156     */
157     
158     load : function(url)
159     {
160         this.url = url || this.url;
161         if (!this.url) {
162             return;
163         }
164         // reset stufff..
165         this.doc = false;
166         this.sheet = false;
167         this.grid = false;
168         this.colInfo = false;
169         this.colInfoDom = false;
170         this.rowInfo = false;
171         this.rowInfoDom = false;
172         this.cmax = false;
173         this.rmax = false;
174         
175         if (this.stylesheetID) {
176             
177             Roo.util.CSS.removeStyleSheet(this.stylesheetID);
178             this.stylesheetID = false;
179             
180         }
181         
182         _t = this;
183         var c = new Roo.data.Connection();
184         c.request({
185             url: this.url,
186             method:  'GET',
187             success : function(resp, opts) {
188                 _t.response = resp;
189                 _t.doc = resp.responseXML;
190                 
191                 _t.parseDoc(0);
192                 
193                 
194                 _t.applyData();
195     
196                 _t.fireEvent('load', _t);
197             },
198             failure : function()
199             {
200                 Roo.MessageBox.alert("Error", "Failed to Load Template for Spreadsheet");
201             }
202         });
203         
204
205     },
206     
207     
208      
209     RCtoCell : function(r,c)
210     {
211         // we wil only support AA not AAA
212         var top = Math.floor(c/26);
213         var bot = c % 26;
214         var cc = top > 0 ? String.fromCharCode('A'.charCodeAt(0) + top) : '';
215         cc += String.fromCharCode('A'.charCodeAt(0)  + bot);
216         return cc+'' +r;
217         
218     },
219     
220     /**
221      * toRC:
222      * convert 'A1' style position to row/column reference
223      * 
224      * @arg {String} k cell name
225      * @return {Object}  as { r: {Number} , c: {Number}  }
226      */
227     
228     toRC : function(k)
229     {
230         var c = k.charCodeAt(0)-64;
231         var n = k.substring(1);
232         if (k.charCodeAt(1) > 64) {
233             c *=26;
234             c+=k.charCodeAt(1)-64;
235             n = k.substring(2);
236         }
237         return { c:c -1 ,r: (n*1)-1 }
238     },
239       /**
240      * rangeToRC:
241      * convert 'A1:B1' style position to array of row/column references
242      * 
243      * @arg {String} k cell range
244      * @return {Array}  as [ { r: {Number} , c: {Number}  }. { r: {Number} , c: {Number}  } ]
245      */
246     rangeToRC : function(s) {
247         var ar = s.split(':');
248         return [ this.toRC(ar[0]) , this.toRC(ar[1])]
249     },
250     
251     
252     
253    
254     
255     /**
256      * parseDoc:
257      * convert XML document into cells and other data..
258      * 
259      */
260     parseDoc : function(sheetnum) 
261     {
262         var _t = this;
263         this.grid = {}
264         this.rmax = 1;
265         this.cmax = 1;
266         
267         this.sheet = _t.doc.getElementsByTagNameNS('*','Sheet')[sheetnum];
268         
269         
270         this.cellholder = this.sheet.getElementsByTagNameNS('*','Cells')[0];
271         var cells = this.sheet.getElementsByTagNameNS('*','Cell');
272
273         
274         
275         Roo.each(cells, function(c) {
276            // Roo.log(c);
277             var row = c.getAttribute('Row') * 1;
278             var col = c.getAttribute('Col') * 1;
279             _t.cmax = Math.max(col+1, _t.cmax);
280             _t.rmax = Math.max(row+1, _t.rmax);
281             var vt = c.getAttribute('ValueType');
282             var vf = c.getAttribute('ValueFormat');
283             var val = c.textContent;
284             
285             if (typeof(_t.grid[row]) == 'undefined') {
286                 _t.grid[row] ={};
287             }
288             _t.grid[row][col] = Roo.applyIf({
289                 valueType : vt,
290                 valueFormat : vf,
291                 value : val,
292                 dom: c,
293                 r: row,
294                 c: col
295             }, _t.defaultCell);
296         });
297        
298         for (var r = 0; r < this.rmax;r++) {
299             if (typeof(this.grid[r]) == 'undefined') {
300               this.grid[r] ={};
301             }
302             for (var c = 0; c < this.cmax;c++) {
303                 if (typeof(this.grid[r][c]) == 'undefined') {
304                     continue;
305                 }
306                 //this.print( "[" + r + "]["+c+"]=" + grid[r][c].value +'<br/>');
307             }
308         }
309         
310         var merge = this.sheet.getElementsByTagNameNS('*','Merge');
311
312         Roo.each(merge, function(c) {
313             var rc = _t.rangeToRC(c.textContent);
314             //Roo.log(JSON.stringify(rc));
315             if (typeof(_t.grid[rc[0].r][rc[0].c]) == 'undefined') {
316                 //Roo.log(["creating empty cell for  ",rc[0].r,  rc[0].c ]);
317                  _t.createCell(rc[0].r,  rc[0].c );
318                 //_t.grid[rc[0].r][rc[0].c] =  //Roo.applyIf({ r : rc[0].r, c : rc[0].c }, _t.defaultCell);
319             }
320                 
321             _t.grid[rc[0].r][rc[0].c].colspan = (rc[1].c - rc[0].c) + 1;
322             _t.grid[rc[0].r][rc[0].c].rowspan = (rc[1].r - rc[0].r) + 1;
323             for(var r = (rc[0].r); r < (rc[1].r+1); r++) {
324                for(var cc = rc[0].c; cc < (rc[1].c+1); cc++) {
325                     //Roo.log('adding alias : ' + r+','+c);
326                    _t.grid[r][cc] = _t.grid[rc[0].r][rc[0].c];
327                }
328            }
329             
330             
331         });
332         // read colinfo..
333         var ci = this.sheet.getElementsByTagNameNS('*','ColInfo');
334         this.colInfo = {};
335         this.colInfoDom = {};
336         
337         Roo.each(ci, function(c) {
338             var count = c.getAttribute('Count') || 1;
339             var s =  c.getAttribute('No')*1;
340             for(var i =0; i < count; i++) {
341                 _t.colInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
342                 _t.colInfoDom[s+i] = c;
343             }
344         });
345         
346         
347         ci = this.sheet.getElementsByTagNameNS('*','RowInfo');
348         
349         this.rowInfo = {};
350         this.rowInfoDom = {};
351         Roo.each(ci, function(c) {
352             var count = c.getAttribute('Count') || 1;
353             var s =  c.getAttribute('No')*1;
354             for(var i =0; i < count; i++) {
355                 _t.rowInfoDom[s+i] = c;
356                 _t.rowInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
357             }
358         });
359     
360         _t.parseStyles();
361         _t.overlayStyles();
362                 
363         
364      
365         
366     },
367      /**
368      * overlayStyles:
369      * put the style info onto the cell data.
370      * 
371      */
372     overlayStyles : function ()
373     {
374            // apply styles.
375         var _t = this;
376         Roo.each(this.styles, function(s) {
377        
378             for (var r = s.r; r < s.r1;r++) {
379                 if (typeof(_t.grid[r]) == 'undefined') {
380                    continue;
381                 }
382                 for (var c = s.c; c < s.c1;c++) {
383                     if (c > _t.cmax) continue;
384     
385                     if (typeof(_t.grid[r][c]) == 'undefined') {
386                         _t.createCell(r,c);
387                         //_t.grid[r][c] = Roo.applyIf({ r: r , c : c }, _t.defaultCell);
388                     }
389                     var g=_t.grid[r][c];
390                     if (typeof(g.cls) =='undefined') {
391                         g.cls = [];
392                         g.styles = [];
393                     }
394                     if (g.cls.indexOf(s.name)  > -1) continue;
395                     g.cls.push(s.name);
396                     g.styles.push(s.dom);
397                     
398                 }
399             }
400         });
401     },
402      /**
403      * parseStyles: 
404      *  read the style information
405      * generates a stylesheet for the current file
406      * this should be disposed of really.....
407      * 
408      */
409     parseStyles : function() {
410                 
411         var srs = this.sheet.getElementsByTagNameNS('*','StyleRegion');
412         var _t  = this;
413         var ent = {};
414         
415         var map =  {
416             HAlign : function(ent,v) { 
417                 ent['text-align'] = { '1' : 'left', '8': 'center', '4' : 'right'}[v] || 'left';
418             },
419             VAlign : function(ent,v) { 
420                 ent['vertical-align'] = { '1' : 'top', '4': 'middle', '8' : 'bottom'}[v]  || 'top'
421             },
422             Fore : function(ent,v) { 
423                 var col=[];
424                 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
425                 ent['color'] = 'rgb(' + col.join(',') + ')';
426             },
427             Back : function(ent,v) { 
428                 var col=[];
429                 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
430                 ent['background-color'] = 'rgb(' + col.join(',') + ')';
431             },
432             FontUnit : function(ent,v) { 
433                 ent['font-size'] = v + 'px';
434             },
435             FontBold : function(ent,v) { 
436                 if (v*1 < 1) return;
437                 ent['font-weight'] = 'bold';
438             },
439             FontItalic : function(ent,v) { 
440                 if (v*0 < 1) return;
441                 //ent['font-weight'] = 'bold';
442             },
443             FontName : function(ent,v) { 
444                 ent['font-family'] = v;
445             },
446             BorderStyle : function(ent,v) { 
447                 var vv  = v.split('-');
448                 ent['border-'+vv[0]+'-style'] = 'solid';
449                 ent['border-'+vv[0]+'-width'] = vv[1]+'px';
450             },
451             BorderColor : function(ent,v) { 
452                 var vv  = v.split('-');
453                 var col=[];
454                 Roo.each(vv[1].split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
455                 ent['border-'+vv[0]+'-color'] = 'rgb(' + col.join(',') + ')';
456             }
457         };
458         function add(e, k, v) {
459             //Roo.log(k,v);
460             e.gstyle[k] = v;
461             if (typeof(map[k]) == 'undefined') {
462                 return;
463             }
464             map[k](e.style,v);    
465         }
466         var css = {};
467         var styles = [];
468         var sid= Roo.id();
469         
470         
471         Roo.each(srs, function(sr,n)
472         {
473             ent = {
474                 c : sr.getAttribute('startCol') *1,
475                 r : sr.getAttribute('startRow')*1,
476                 c1 : (sr.getAttribute('endCol')*1) +1,
477                 r1 : (sr.getAttribute('endRow')*1) +1,
478                 style : {},  // key val of style for HTML..
479                 gstyle : {}, // key val of attributes used..
480                 name : sid +'-gstyle-' + n,
481                 dom : sr
482                 
483             };
484     
485             Roo.each(sr.getElementsByTagNameNS('*','Style')[0].attributes, function(e) { 
486                 add(ent, e.name, e.value);
487             });
488             if (sr.getElementsByTagNameNS('*','Font').length) {
489                 Roo.each(sr.getElementsByTagNameNS('*','Font')[0].attributes, function(e) { 
490                      add(ent, 'Font'+e.name, e.value);
491     
492                 });
493                 add(ent, 'FontName', sr.getElementsByTagNameNS('*','Font')[0].textContent);
494     
495             }
496             if (sr.getElementsByTagNameNS('*','StyleBorder').length) {
497                 Roo.each(sr.getElementsByTagNameNS('*','StyleBorder')[0].childNodes, function(e) {
498                     if (!e.tagName) {
499                         return;
500                     }
501                     Roo.each(e.attributes, function(ea) { 
502                         add(ent, 'Border'+ea.name, e.tagName.split(':')[1].toLowerCase() + '-' + ea.value);
503                     });
504                 })
505                     
506             }
507             styles.push(ent);
508             css['.'+ent.name] = ent.style;
509         });
510         
511         this.styles = styles;
512         
513         this.stylesheetID = sid;
514         Roo.util.CSS.createStyleSheet(css, sid);
515     },
516
517     
518     
519     
520     /* ---------------------------------------  AFTER LOAD METHODS... ----------------------- */
521     /**
522      * set: 
523      * Set the value of a cell..
524      * @param {String} cell name of cell, eg. C10 or { c: 1, r :1 }
525          
526      * @param {Value} value to put in cell..
527      * @param {ValueType} type of value
528      * @param {ValueFormat} value format of cell
529      * 
530      * Cells should exist at present, we do not make them up...
531      */
532      
533     
534     set : function(cell, v, vt, vf) {
535         
536         var cs= typeof(cell) == 'string' ? this.toRC(cell) : cell;
537         
538         
539         Roo.log( cs.r+ ',' + cs.c + ' = '+ v);
540         // need to generate clell if it doe
541         if (typeof(this.grid[cs.r]) == 'undefined') {
542             Roo.log('no row:' + cell);
543             this.grid[cs.r] = []; // create a row..
544             //return;
545         }
546         if (typeof(this.grid[cs.r][cs.c]) == 'undefined') {
547             Roo.log('cell not defined:' + cell);
548             this.createCell(cs.r,cs.c);
549         }
550         // cell might not be rendered yet... so if we try and create a cell, it overrides the default formating..
551         
552         if (typeof(this.grid[cs.r][cs.c].dom) == 'undefined') {
553             Roo.log('no default content for cell:' + cell);
554             Roo.log(this.grid[cs.r][cs.c]);
555             //this.createCell(cs.r,cs.c);
556             //return;
557         }
558         this.grid[cs.r][cs.c].value=  v;
559         if (this.grid[cs.r][cs.c].dom) {
560             this.grid[cs.r][cs.c].dom.textContent=  v;
561         }
562         
563         
564         if (typeof(vt) != 'undefined') {
565             this.grid[cs.r][cs.c].valueType = vt;
566             this.grid[cs.r][cs.c].dom.setAttribute('ValueType', vt);
567             if (vt === '' || vt === false) { // value type is empty for formula's
568                 this.grid[cs.r][cs.c].dom.removeAttribute('ValueType');
569             }
570         }
571         if (typeof(vf) != 'undefined' && vf !== false) {
572             this.grid[cs.r][cs.c].valueFormat = vf;
573             this.grid[cs.r][cs.c].dom.setAttribute('ValueFormat', vf);
574             if (vf === '' || vf === false) { // value type is empty for formula's
575                 this.grid[cs.r][cs.c].dom.removeAttribute('ValueFormat');
576             }
577         }
578         
579     },
580     
581     // private
582     copyRow : function(src, dest) {
583         if (dest == src) {
584             return;
585         }
586        // Roo.log('create Row' + dest);
587         if (typeof(this.grid[dest]) == 'undefined') {
588             this.grid[dest] = {}
589         }
590         
591            
592         for (var c = 0; c < this.cmax; c++) {
593
594             this.copyCell({ r: src, c: c } , { r: dest, c: c});
595             
596         }
597         this.rmax = Math.max(this.rmax, dest +1);
598         
599     },
600     
601     // private
602     
603     createCell: function(r,c)
604     {
605         //<gnm:Cell Row="6" Col="5" ValueType="60">Updated</gnm:Cell>    
606         var nc = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Cell');
607         this.cellholder.appendChild(nc);
608         var lb = this.doc.createTextNode("\n");// add a line break..
609         this.cellholder.appendChild(lb);
610         
611         nc.setAttribute('Row', new String(r));
612         nc.setAttribute('Col', new String(c));
613         nc.setAttribute('ValueType', '60');
614         nc.textContent = '';
615         
616         this.grid[r][c] = Roo.applyIf({
617             valueType : '60',
618             valueFormat : '',
619             value : '',
620             dom: nc,
621             r: r,
622             c: c
623             }, _t.defaultCell);
624         
625         return nc;
626
627     },
628     
629     // private
630     copyCell : function(src, dest)
631     {
632         var old = this.grid[src.r][src.c];
633         // is it an alias...
634         if ((old.c != src.c)  || (old.r != src.r)) {
635             // only really works on horizonatal merges..
636             
637             this.grid[dest.r][dest.c] = this.grid[desc.r][old.c]; // let's hope it exists.
638             return;
639         }
640         
641         
642         var nc = Roo.apply({}, this.grid[src.r][src.c]);
643         
644         nc.value = '';
645         if (typeof(old.dom) == 'undefined') {
646             Roo.log("No cell to copy for " + Roo.encode(src));
647             return;
648         }
649         this.grid[dest.r][dest.c] = nc;
650         nc.dom = old.dom.cloneNode(true);
651         nc.dom.setAttribute('Row', dest.r);
652         nc.dom.setAttribute('Cell', dest.c);
653         nc.dom.textContent = '';
654         old.dom.parentNode.appendChild(nc.dom);
655         if (!old.styles || !old.styles.length) {
656             return;
657         }
658         //Roo.log("DEST");
659         //Roo.log(dest);
660         //Roo.log("STYLES");
661         //  .styles...
662         Roo.each(old.styles, function(s) {
663             // try and extend existing styles..
664             var er = s.getAttribute('endRow') * 1;
665             var ec = s.getAttribute('endCol') * 1;
666             //Roo.log(s);
667             if (dest.r == er) {
668                 s.setAttribute('endRow', dest.r + 1);
669             }
670             if (dest.c == ec) {
671                 s.setAttribute('endCol', dest.c + 1);
672             }
673             /*var ns = s.cloneNode(true);
674             s.parentNode.appendChild(ns);
675             ns.setAttribute('startCol', dest.c);
676             ns.setAttribute('startRow', dest.r);
677             ns.setAttribute('endCol', dest.c + 1);
678             ns.setAttribute('endRow', dest.r +1);
679             */
680         });
681         
682     },
683     
684     
685     /**
686      * applyData: 
687      * Set the value of a cell..
688      * @param {String} cell name of cell, eg. C10
689      * @param {Value} value to put in cell..
690      * 
691      * Cells should exist at present, we do not make them up...
692      */
693      
694     applyData : function(data)
695     {
696         
697         data = data || this.data;
698         for (var r = 0; r < this.rmax;r++) {
699             if (typeof(this.grid[r]) == 'undefined') continue;
700             for (var c = 0; c < this.cmax;c++) {  
701                 if (typeof(this.grid[r][c]) == 'undefined') {
702                     continue;
703                 }
704                 if (!this.grid[r][c].value.length 
705                         || !this.grid[r][c].value.match(/\{/)) {
706                     continue;
707                 }
708                 
709                 var x = new Roo.Template({ html: this.grid[r][c].value });
710                 try {
711                     var res = x.applyTemplate(data);
712                     //Roo.log("set " + r  + "," + c + ":"+res)
713                     this.set({ r: r, c: c}, x.applyTemplate(data));
714                 } catch (e) {
715                  //   Roo.log(e.toString());
716                   //  Roo.log(e);
717                     // continue?
718                 }
719                 
720             }
721         }
722             
723     },
724     
725     readTableData : function(table)
726     {
727         // read the first row.
728         var tds = Roo.get(table).select('tr').item(0).select('td');
729         var maxnc = 0;
730         
731         Roo.get(table).select('tr').each(function(trs) {
732             var nc = 0;
733            
734             trs.select('td').each(function(td) {
735                 var cs = td.dom.getAttribute('colspan');
736                 cs = cs ? cs * 1 : 1;
737                 nc += cs;
738             });
739             maxnc = Math.max(nc, maxnc);
740         });
741         
742         var tr = document.createElement('tr');
743         table.appendChild(tr);
744         var ar = {};
745         for (i =0; i < maxnc; i++) {
746             ar[i] = document.createElement('td');
747             tr.appendChild(ar[i]);
748         }
749         // find the left.
750         var ret = { cols : maxnc, pos : {} };
751         for (i =0; i < maxnc; i++) {
752             ret.pos[ Roo.get(ar[i]).getLeft()] =i;
753         }
754         ret.near = function(p) {
755             // which one is nearest..
756             
757             if (this.pos[p]) {
758                 return this.pos[p];
759             }
760             var prox = 100000;
761             var match = 0;
762             for(var i in this.pos) {
763                 var dis = Math.abs(p-i);
764                 if (dis < prox) {
765                     prox = dis;
766                     match = this.pos[i];
767                 }
768             }
769             return match;
770             
771         }
772         table.removeChild(tr);
773         return ret;
774     },
775     
776      
777    
778      
779     /**
780      * importTable: 
781      * Import a table and put it into the spreadsheet
782      * @param {HTMLTable} datagrid dom element of html table.
783      * @param {Number} xoff X offset to start rendering to
784      * @param {Number} yoff Y offset to start rendering to
785      **/
786      
787  
788     importTable : function (datagrid, xoff,yoff)
789     {
790         if (!datagrid) {
791             Roo.log("Error table not found!?");
792             return;
793         }
794         xoff = xoff || 0;
795         yoff = yoff || 0;
796         
797         
798         var table_data = this.readTableData(datagrid);
799         
800         // oroginally this cleaned line breaks, but we acutally need them..
801         var cleanHTML = function (str) {
802             
803             var ret = str;
804             ret = ret.replace(/&nbsp;/g,' ');
805            // ret = ret.replace(/\n/g,'.');
806           //  ret = ret.replace(/\r/g,'.');
807             var i;
808              
809             return ret;
810         };
811
812         
813         // <cell col="A" row="1">Test< / cell>
814         // <cell col="B" row="2" type="Number" format="test1">30< / cell>
815         var rowOffsets = {};
816         var rows = datagrid.getElementsByTagName('tr');
817         //alert(rows.length);
818         
819         
820         for(var row=0;row<rows.length;row++) {
821             
822             // let's see what affect this has..
823             // it might mess things up..
824             
825             if (rows[row].getAttribute('xls:height')) {
826                 this.setRowHeight(row + yoff +1, 1* rows[row].getAttribute('xls:height'));
827             } else {
828                 this.setRowHeight( row + yoff +1, Roo.get(rows[row]).getHeight());
829             }
830             
831          
832             var cols = rows[row].getElementsByTagName('td');
833             
834             
835             for(var col=0;col < cols.length; col++) {
836                 
837                 
838                
839                 
840                 var colspan = cols[col].getAttribute('colspan');
841                 colspan  = colspan ? colspan *1 : 1;
842                 
843                 var rowspan = cols[col].getAttribute('rowspan');
844                 rowspan = rowspan ? rowspan * 1 : 1;
845                 
846                 var realcol = table_data.near( Roo.get(cols[col]).getLeft() );
847                 
848                 
849                 
850                 if (colspan > 1 || rowspan > 1) {
851                     
852                     // getting thisese right is tricky..
853                     this.mergeRegion(
854                         realcol + xoff,
855                         row + yoff +1,
856                         realcol+ xoff + (colspan -1),
857                         row + yoff + rowspan 
858                     );
859                     
860                 }
861                 
862                 // skip blank cells
863                 // set the style first..
864                 this.parseHtmlStyle( cols[col], row + yoff, realcol + xoff   , colspan, rowspan);
865                 
866                 if (!cols[col].childNodes.length) {
867                      
868                     continue;
869                 }
870                 
871                 
872                 
873                 
874                 var vt = '60';
875                 var vf = false;
876                 var xlstype = cols[col].getAttribute('xls:type');
877                 switch(xlstype) {
878                     case 'int':
879                         vt = 30; // int!!!!
880                     
881                         break;
882                         
883                     case 'float':
884                         vt = 40; // float!!!!
885                         if (cols[col].getAttribute('xls:floatformat')) {
886                             vf = cols[col].getAttribute('xls:floatformat');
887                         }
888                         break;
889                         
890                     case 'date':
891                         vt = 30;
892                         //ValueFormat="d/m/yyyy" 38635  
893                         var vf = 'd/m/yyy';
894                         if (cols[col].getAttribute('xls:dateformat')) {
895                             vf= cols[col].getAttribute('xls:dateformat');
896                         }
897                         
898                        
899                         
900                         break;
901                     
902                     default:
903                        
904                         break;
905                 }
906                
907                 if (!cols[col].childNodes[0].nodeValue) {
908                    
909                     continue;
910                 }
911                 if (!cols[col].childNodes[0].nodeValue.replace(/^\s*|\s*$/g,"").length) {
912                   
913                     continue;
914                 }
915                 // strip me.!
916                 var cell_value_text = cleanHTML(cols[col].childNodes[0].nodeValue);
917        
918                 if (cols[col].getAttribute('xls:percent')) {
919                     cell_value_text = '' + ((cell_value_text * 1) / 100);
920                 }
921
922                 if (cell_value_text.length && (vt == 30) && xlstype == 'date') {
923                     var bits = cell_value_text.split(/-/);
924                     var cur = new Date(bits[0],bits[1]-1,bits[2]);
925                     cell_value_text = '' + Math.round((cur.getTime() - Date.UTC(1899,11,30)) / (24 * 60 * 60 * 1000));
926                 }
927
928                 
929                 
930                 if (cols[col].getAttribute('xls:formula')) {
931                     var s = cols[col].getAttribute('xls:formula');
932                     vt = '';
933                     cell_value_text = s.replace(/#row#/g,(row + yoff + 1));
934                 }
935                 this.set({ r: row + yoff, c : realcol + xoff }, cell_value_text, vt, vf);
936                  
937                   
938                 
939                 
940                 
941             }
942         }
943         this.rowOffset += rows.length;
944         
945     },
946     
947     
948     
949     parseHtmlStyle : function(dom, row, col, colspan, rowspan) {
950         
951         function toCol (rgb) {
952             
953             var ar = rgb.replace(/rgb[a]?\(/, '').replace(/\)/, '').replace(/ /, '').split(',');
954             var rcs = [];
955             ar = ar.slice(0,3);
956             Roo.each(ar, function(c) { 
957                 rcs.push((c*c).toString(16)) ;   
958             });
959             return rcs.join(':');
960             
961         }
962         
963         var el = Roo.get(dom);
964         var map =  {
965             'text-align'  : function(ent,v) { 
966                 ent['HAlign'] = { 'left' : '1', 'center' : '8' ,  'right' : '4' }[v] || '1';
967             },
968             'vertical-align': function(ent,v) { 
969                 ent['VAlign'] = { 'top' : '1', 'middel' : '8' ,  'bottom' : '4' }[v] || '1';
970             },
971             
972             'color': function(ent,v) { 
973                 ent['Fore'] = toCol(v);
974                 // this is a bit dumb.. we assume that if it's not black text, then it's shaded..
975                 if (ent['Fore'] != '0:0:0') {
976                     ent['Shade'] = 1;
977                 }
978                 
979             },
980             'background-color' : function(ent,v) { 
981                 ent['Back'] = toCol(v);
982                  
983             }
984             
985         };
986        
987         var ent = {
988                 HAlign:"1",
989                 VAlign:"2",
990                 WrapText:"0",
991                 ShrinkToFit:"0",
992                 Rotation:"0",
993                 Shade:"0",
994                 Indent:"0",
995                 Locked:"0",
996                 Hidden:"0",
997                 Fore:"0:0:0",
998                 Back:"FFFF:FFFF:FFFF",
999                 PatternColor:"0:0:0",
1000                 Format:"General"
1001         };
1002            
1003         for(var k in map) {
1004             var val = el.getStyle(k);
1005             if (!val || !val.length) {
1006                continue;
1007             }
1008             map[k](ent,val);
1009         }
1010         // special flags..
1011         if (el.dom.getAttribute('xls:wraptext')) {
1012             ent.WrapText = 1;
1013         }
1014         if (el.dom.getAttribute('xls:valign')) {
1015             ent.VAlign= 1;
1016         }
1017         if (el.dom.getAttribute('xls:halign')) {
1018             ent.HAlign= 1;
1019         }
1020         // fonts..
1021         var fmap = {
1022             
1023            
1024             'font-size' : function(ent,v) { 
1025                 ent['Unit'] = v.replace(/px/, '');
1026             },
1027             'font-weight' : function(ent,v) { 
1028                 if (v != 'bold') return;
1029                 ent['Bold'] = 1;
1030             },
1031             'font-style' : function(ent,v) { 
1032                 if (v != 'italic') return;
1033                 ent['Italic'] = 1;
1034             } 
1035         }
1036        
1037         var fent = {
1038             Unit:"10",
1039             Bold:"0",
1040             Italic:"0",
1041             Underline:"0",
1042             StrikeThrough:"0"
1043         };
1044         
1045         for(var k in fmap) {
1046             var val = el.getStyle(k);
1047             if (!val || !val.length) {
1048                continue;
1049             }
1050             fmap[k](fent,val);
1051         }
1052         var font = el.getStyle('font-family') || 'Sans';
1053         if (font.split(',').length > 1) {
1054             font = font.split(',')[1].replace(/\s+/, '');
1055         }
1056         
1057         
1058         /// -- now create elements..
1059         
1060         var objs = this.sheet.getElementsByTagNameNS('*','Styles')[0];
1061         
1062         //<gnm:StyleRegion startCol="0" startRow="0" endCol="255" endRow="65535"
1063         var sr = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:StyleRegion');
1064         objs.appendChild(sr);
1065         objs.appendChild(this.doc.createTextNode("\n"));// add a line break..
1066
1067         sr.setAttribute('startCol', col);
1068         sr.setAttribute('endCol', col+ colspan-1);
1069         sr.setAttribute('startRow', row);
1070         sr.setAttribute('endRow', row + rowspan -1);
1071         
1072         
1073         var st = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Style');
1074         sr.appendChild(st);
1075         // do we need some defaults..
1076         for(var k in ent) {
1077             //Roo.log(k);
1078             st.setAttribute(k, ent[k]);
1079         }
1080         
1081         var fo = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Font');
1082         st.appendChild(fo);
1083         // do we need some defaults..
1084         for(var k in fent) {
1085             fo.setAttribute(k, fent[k]);
1086         }
1087         fo.textContent  = font;
1088         
1089         var sb = false;
1090         // borders..
1091         Roo.each(['top','left','bottom','right'], function(p) {
1092             var w = el.getStyle('border-' + p + '-width').replace(/px/, '');
1093             if (!w || !w.length || (w*1) < 1) {
1094                 return;
1095             }
1096             if (!sb) {
1097                 sb= this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:StyleBorder');
1098             }
1099             var be = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:' + p[0].toUpperCase() + p.substring(1));
1100             be.setAttribute('Style', '1');
1101             be.setAttribute('Color', '0:0:0'); // fixme..
1102             sb.appendChild(be);
1103             
1104         }, this);
1105         // start adding them all together..
1106         
1107         if (sb) {
1108             st.appendChild(sb);
1109         }
1110         
1111         
1112         
1113         
1114     },
1115     
1116     
1117     
1118     /**
1119      * writeImage:
1120      * write an image (needs base64 data to write it)
1121      * 
1122      * 
1123      * @param {Number} row  row to put it in (rows start at 0)
1124      * @param {Number} col  column to put it in
1125      * @param {Number} data  the base64 description of the images
1126      * @param {Number} width image width
1127      * @param {Number} width image height
1128      * 
1129      */
1130     
1131     
1132     writeImage : function (row, col, data, width, height) 
1133     {
1134         
1135         // our default height width is 50/50 ?!
1136         //console.log('w='+width+',height='+height);
1137                 //        <gmr:Objects>
1138         row*=1;
1139         col*=1;
1140         height*=1;
1141         width*=1;
1142         var objs = this.sheet.getElementsByTagNameNS('*','Objects')[0];
1143         var soi = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:SheetObjectImage');
1144         
1145         //<gmr:SheetObjectImage 
1146         //      ObjectBound="A3:J8" 
1147         //      ObjectOffset="0.375 0.882 0.391 0.294" 
1148         //      ObjectAnchorType="16 16 16 16" 
1149         //      Direction="17" 
1150         //      crop-top="0.000000" 
1151         //      crop-bottom="0.000000" 
1152         //      crop-left="0.000000" 
1153         //      crop-right="0.000000">
1154                 
1155                 
1156         //alert(gnumeric_colRowToName(row,col));
1157                
1158         // this is where we really have fun!!!... 
1159         // since our design currently assumes the height is enough to fit
1160         // stuff in, we only really need to work out how wide it has to be..
1161         
1162         // note we should probably use centralized calcs if it fits in the first cell!
1163         
1164         // step 1 - work out how many columns it will span..
1165         // lets hope the spreadsheet is big enought..
1166         var colwidth = 0;
1167         var endcol=col;
1168         for ( endcol=col;endcol <100; endcol++) {
1169             if (!this.colInfo[endcol]) {
1170                 this.colInfo[endcol] = 100; // eak fudge
1171             }
1172             colwidth += this.colInfo[endcol];
1173             if (colwidth > width) {
1174                 break;
1175             }
1176         }
1177        
1178         
1179         soi.setAttribute('ObjectBound',
1180             //gnumeric_colRowToName(row,col) + ':' + gnumeric_colRowToName(row+1,col+1));
1181             this.RCtoCell(row,col) + ':' + this.RCtoCell(row,endcol));
1182      
1183         var ww = 0.01; // offset a bit...
1184         var hh = 0.01; //
1185         
1186         var ww2 = 1 - ((colwidth - width) / this.colInfo[endcol]);
1187         var hh2 = 0.99;
1188         
1189         var offset_str = ww + ' '  + hh + ' ' + ww2 + ' '+hh2;
1190         //console.log(offset_str );
1191         //alert(offset_str);
1192         soi.setAttribute('ObjectOffset', offset_str);
1193         soi.setAttribute('ObjectAnchorType','16 16 16 16');
1194         soi.setAttribute('Direction','17');
1195         soi.setAttribute('crop-top','0.000000');
1196         soi.setAttribute('crop-bottom','0.000000');
1197         soi.setAttribute('crop-left','0.000000');
1198         soi.setAttribute('crop-right','0.000000');
1199                 // <Content image-type="jpeg" size-bytes="3900">......  < / Content>
1200         var content = this.doc.createElement('Content');
1201         content.setAttribute('image-type','jpeg');
1202         //alert(imgsrc);
1203         
1204         content.setAttribute('size-bytes',data.length);
1205         content.textContent = data;
1206         soi.appendChild(content);
1207         objs.appendChild(soi);
1208         return true;
1209                 //< /gnm:SheetObjectImage>
1210                 // < /gnm:Objects>
1211
1212     },
1213  
1214     /**
1215      * mergeRegion:
1216      * Merge cells in the spreadsheet. (does not check if existing merges exist..)
1217      * 
1218      * @param {Number} col1  first column 
1219      * @param {Number} row1  first row
1220      * @param {Number} col2  to column 
1221      * @param {Number} row2  to row
1222      * 
1223      */
1224     mergeRegion : function (col1,row1,col2,row2)
1225     {
1226         var cell = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Merge');
1227         //if (col1 > 50|| col2 > 50) { // do not merge cols off to right?
1228        //     return;
1229         //}
1230         
1231         cell.textContent = this.RCtoCell(row1,col1) + ':' + this.RCtoCell(row2,col2);
1232         
1233         //var merges = this.gnumeric.getElementsByTagNameNS('*','MergedRegions');
1234         var merges = this.sheet.getElementsByTagNameNS('*','MergedRegions');
1235         if (!merges || !merges.length) {
1236             merges = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd','gnm:MergedRegions');
1237             var sl = this.sheet.getElementsByTagNameNS('*','SheetLayout')[0];
1238             this.sheet.insertBefore(merges,sl);
1239         } else {
1240             merges = merges[0];
1241         }
1242         merges.appendChild(cell);
1243     
1244     },
1245     /**
1246      * setRowHeight:
1247      * Sets the height of a row.
1248      * 
1249      * @param {Number} r  the row to set the height of. (rows start at 0)
1250      * @param {Number} height (in pixels)
1251      */
1252     setRowHeight : function (r,height)
1253     {
1254         
1255         //<gmr:Rows DefaultSizePts="12.75">
1256         //   <gmr:RowInfo No="2" Unit="38.25" MarginA="0" MarginB="0" HardSize="1"/>
1257     //  < /gmr:Rows>
1258         
1259         // this doesnt handle row ranges very well.. - with 'count in them..'
1260         
1261         if (this.rowInfoDom[r]) {
1262             this.rowInfoDom[r].setAttribute('Unit', height);
1263             return;
1264         }
1265     
1266         var rows = this.sheet.getElementsByTagNameNS('*','Rows')[0]; // assume this exists..
1267         var ri = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd','gnm:RowInfo');
1268         // assume we have no rows..
1269         ri.setAttribute('No', r-1);
1270         ri.setAttribute('Unit', height);
1271         ri.setAttribute('MarginA', 0);
1272         ri.setAttribute('MarginB', 0);
1273         ri.setAttribute('HardSize', 1);
1274         rows.appendChild(ri);
1275         this.rowInfoDom[r] = ri;
1276     },
1277      
1278     /**
1279      * setSheetName: 
1280      * Set the sheet name.
1281      * @param {String} title for sheet
1282      **/
1283     setSheetName : function(name,sheet)
1284     {
1285         sheet = sheet || 0;
1286         /*
1287         <gnm:SheetNameIndex>
1288         <gnm:SheetName>Sheet1</gnm:SheetName>
1289         <gnm:SheetName>Sheet2</gnm:SheetName>
1290         <gnm:SheetName>Sheet3</gnm:SheetName>
1291         </gnm:SheetNameIndex>
1292         */
1293         // has to set sheet name on index and body..
1294         Roo.log(sheet);
1295         Roo.log(name);
1296         var sheetnames = this.doc.getElementsByTagNameNS('*','SheetName');
1297         if (sheet >=  sheetnames.length) {
1298             
1299             sheetnames[0].parentNode.appendChild(sheetnames[sheetnames.length-1].cloneNode(true));
1300             // copy body.
1301             sheetnames = this.doc.getElementsByTagNameNS('*','Sheet');
1302             sheetnames[0].parentNode.appendChild(sheetnames[sheetnames.length-1].cloneNode(true));
1303             var sn = this.doc.getElementsByTagNameNS('*','Sheet')[sheet];
1304             var cls = sn.getElementsByTagNameNS('*','Cells')[0];
1305             while (cls.childNodes.length) {
1306                 cls.removeChild(cls.firstChild);
1307             }
1308             
1309         }
1310         
1311         var sheetn = this.doc.getElementsByTagNameNS('*','SheetName')[sheet];
1312         sheetn.textContent = name;
1313         var sheetb = this.doc.getElementsByTagNameNS('*','Sheet')[sheet].getElementsByTagNameNS('*','Name')[0];
1314         sheetb.textContent = name;
1315         this.parseDoc(sheet);
1316         
1317         
1318         
1319         
1320     },
1321      /**
1322      * setColumnWidth: 
1323      * Set the column width
1324      * @param {Number} column number (starts at '0')
1325      * @param {Number} width size of column
1326      **/
1327     setColumnWidth : function(column, width)
1328     {
1329         column = column *1; 
1330         width= width*1;
1331         if (typeof(this.colInfoDom[column]) == 'undefined') {
1332             var cols = this.doc.getElementsByTagNameNS('*','Cols')[0];
1333             var ri = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:ColInfo');
1334             ri.setAttribute('No', column);
1335             ri.setAttribute('Unit', width);
1336             ri.setAttribute('MarginA', 2);
1337             ri.setAttribute('MarginB', 2);
1338             ri.setAttribute('HardSize', 1);
1339             cols.appendChild(ri);
1340             this.colInfo[column] = width;
1341             this.colInfoDom[column]  = ri;
1342             return;
1343         }
1344         this.colInfoDom[column].setAttribute('Unit', width);
1345         
1346     },
1347     
1348     
1349     
1350     
1351     
1352      /**
1353      * toHTML: 
1354      * Convert spreadsheet into a HTML table.
1355      */
1356             
1357     toHTML :function()
1358     {
1359          var _t = this;
1360         function calcWidth(sc, span)
1361         {
1362             var n =0;
1363             for(var i =sc; i< sc+span;i++) {
1364                 n+=_t.colInfo[i];
1365             }   
1366             return n;
1367         }
1368         
1369         var grid = this.grid;
1370         // lets do a basic dump..
1371         var out = '<table style="table-layout:fixed;" cellpadding="0" cellspacing="0">';
1372         for (var r = 0; r < this.rmax;r++) {
1373             out += '<tr style="height:'+this.rowInfo[r]+'px;">';
1374             for (var c = 0; c < this.cmax;c++) {
1375                 if (typeof(grid[r][c]) == 'undefined')  {
1376                     this.createCell(r,c);
1377                     
1378                 }
1379                 var g = grid[r][c];
1380                 
1381                 if (typeof(g.cls) =='undefined') g.cls = [];
1382                 var w= calcWidth(c,g.colspan);
1383                 
1384                 var value = g.value[0] == '=' ? 'CALCULATED' : g.value;
1385                 
1386                 try {
1387                     if(
1388                         g.styles[0].firstElementChild.getAttribute('Format') == "D\\-MMM\\-YYYY;@" &&
1389                         g.value[0] != '=' &&
1390                         !isNaN(value * 1) && 
1391                         value != 0
1392                     ){
1393                         value = new Date(value * 24 * 60 * 60 * 1000 + new Date('1899-12-30').getTime()).format('d-M-Y');
1394                     }
1395                     
1396                 } catch(e) {
1397                     
1398                 }
1399                 
1400                 out+=String.format('<td colspan="{0}" rowspan="{1}"  class="{4}"><div style="{3}">{2}</div></td>', 
1401                     g.colspan, g.rowspan, value,
1402                     'overflow:hidden;' + 
1403                     'width:'+w+'px;' +
1404                    
1405                     'text-overflow:ellipsis;' +
1406                     'white-space:nowrap;',
1407                      g.cls.join(' ')
1408     
1409     
1410                 );
1411                 c+=(g.colspan-1);
1412             }
1413             out += '</tr>';
1414         }
1415         //Roo.log(out);
1416         return out+'</table>';
1417         
1418         
1419         
1420     },
1421     /**
1422      * download:
1423      * @param {String} name  filename to downlaod (without xls)
1424      * @param {String} callback  (optional) - callback to call after callback is complete.
1425      */
1426     download : function(name,callback)
1427     {
1428         name = name || "Missing_download_filename";
1429         
1430         if (this.downloadURL && this.downloadURL.charAt(this.downloadURL.length-1) != '/') {
1431             this.downloadURL += '/';
1432         }
1433         
1434         var ser = new XMLSerializer();
1435         var x = new Pman.Download({
1436             method: 'POST',
1437             timeout : 120000, // quite a long wait.. 2 minutes.
1438             params : {
1439                xml : ser.serializeToString(this.doc),
1440                format : 'xls', //xml
1441                debug : 0
1442                
1443             },
1444             url : (this.downloadURL || (baseURL + '/GnumericToExcel/')) + name + '.xls',
1445             success : function() {
1446                 Roo.MessageBox.alert("Alert", "File should have downloaded now");
1447                 if (callback) {
1448                     callback();
1449                 }
1450             }
1451         });
1452          
1453     }
1454
1455 });