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