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