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