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