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