1 //<script type="text/javascript">
3 * @class Pman Gnumeric.
4 *-> load up a remote xml file of a gnumeric document.
6 * -> convert into a usable data structure
8 * -> ?? apply templated values ??
9 * -> allow modification of fields
11 * -> render to screen.
13 * -> send for conversion to XLS (via ssconvert)
19 url: rootURL + '/xxx/yyy/templates/reports/myreport.xml',
25 x.applyData({ ... }); // key value data looks for {value} in strings and replaces it..
29 mypanel.update(x.toHTML());
41 * @param {Object} cfg Configuration object.
46 Pman.Gnumeric = function (cfg)
48 cfg.data = cfg.data || {};
58 * Fires when source document has been loaded
59 * @param {Pman.Gnumerci} this
64 Roo.util.Observable.call(this,cfg);
83 Roo.extend(Pman.Gnumeric, Roo.util.Observable, {
86 * @cfg {String} url the source of the Gnumeric document.
90 * @cfg {Object} data overlay data for spreadsheet - from constructor.
94 * @cfg {String} downloadURL where GnumerictoExcel.php is...
100 * @type {XmlDocument} doc the gnumeric xml document
105 * @type {XmlNode} sheet the 'Sheet' element
110 * @type {XmlNode} sheet the 'Cells' element
114 * @type {Object} grid the map[row][col] = cellData
118 * @type {Object} colInfo - list of column sizes
122 * @type {Object} colInfoDom - column sizes dom element
126 * @type {Object} rowInfo - list of row sizes
131 * @type {Number} cmax - maximum number of columns
135 * @type {Object} rmax - maximum number of rows
139 * @type {String} stylesheetID id of stylesheet created to render spreadsheat
141 stylesheetID : false,
143 * @type {Number} rowOffset - used by table importer to enable multiple tables to be improted
150 * run the connection, parse document and fire load event..
151 * can be run multiple times with new data..
157 this.url = url || this.url;
165 this.colInfo = false;
166 this.rowInfo = false;
170 if (this.stylesheetID) {
172 Roo.util.CSS.removeStyleSheet(this.stylesheetID);
173 this.stylesheetID = false;
178 var c = new Roo.data.Connection();
182 success : function(resp, opts) {
184 _t.doc = resp.responseXML;
190 _t.fireEvent('load', _t);
194 Roo.MessageBox.alert("Error", "Failed to Load Template for Spreadsheet");
207 * convert 'A1' style position to row/column reference
209 * @arg {String} k cell name
210 * @return {Object} as { r: {Number} , c: {Number} }
215 var c = k.charCodeAt(0)-64;
216 var n = k.substring(1);
217 if (k.charCodeAt(1) > 64) {
219 c+=k.charCodeAt(1)-64;
222 return { c:c -1 ,r: (n*1)-1 }
226 * convert 'A1:B1' style position to array of row/column references
228 * @arg {String} k cell range
229 * @return {Array} as [ { r: {Number} , c: {Number} }. { r: {Number} , c: {Number} } ]
231 rangeToRC : function(s) {
232 var ar = s.split(':');
233 return [ this.toRC(ar[0]) , this.toRC(ar[1])]
242 * convert XML document into cells and other data..
245 parseDoc : function()
252 this.sheet = _t.doc.getElementsByTagNameNS('*','Sheet')[0];
255 this.cellholder = this.sheet.getElementsByTagNameNS('*','Cells')[0];
256 var cells = this.sheet.getElementsByTagNameNS('*','Cell');
260 Roo.each(cells, function(c) {
262 var row = c.getAttribute('Row') * 1;
263 var col = c.getAttribute('Col') * 1;
264 _t.cmax = Math.max(col+1, _t.cmax);
265 _t.rmax = Math.max(row+1, _t.rmax);
266 var vt = c.getAttribute('ValueType');
267 var vf = c.getAttribute('ValueFormat');
268 var val = c.textContent;
270 if (typeof(_t.grid[row]) == 'undefined') {
273 _t.grid[row][col] = Roo.applyIf({
283 for (var r = 0; r < this.rmax;r++) {
284 if (typeof(this.grid[r]) == 'undefined') {
287 for (var c = 0; c < this.cmax;c++) {
288 if (typeof(this.grid[r][c]) == 'undefined') {
291 //this.print( "[" + r + "]["+c+"]=" + grid[r][c].value +'<br/>');
295 var merge = this.sheet.getElementsByTagNameNS('*','Merge');
297 Roo.each(merge, function(c) {
298 var rc = _t.rangeToRC(c.textContent);
299 //Roo.log(JSON.stringify(rc))
300 if (typeof(_t.grid[rc[0].r][rc[0].c]) == 'undefined') {
301 _t.grid[rc[0].r][rc[0].c] = Roo.applyIf({ r : rc[0].r, c : rc[0].c }, _t.defaultCell);
304 _t.grid[rc[0].r][rc[0].c].colspan = (rc[1].c - rc[0].c) + 1;
305 _t.grid[rc[0].r][rc[0].c].rowspan = (rc[1].r - rc[0].r) + 1;
306 for(var r = (rc[0].r); r < (rc[1].r+1); r++) {
307 for(var c = rc[0].c; c < (rc[1].c+1); c++) {
308 //Roo.log('adding alias : ' + r+','+c);
309 _t.grid[r][c] = _t.grid[rc[0].r][rc[0].c];
316 var ci = this.sheet.getElementsByTagNameNS('*','ColInfo');
318 this.colInfoDom = {};
320 Roo.each(ci, function(c) {
321 var count = c.getAttribute('Count') || 1;
322 var s = c.getAttribute('No')*1;
323 for(var i =0; i < count; i++) {
324 _t.colInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
325 _t.colInfoDom[s+i] = c;
330 ci = this.sheet.getElementsByTagNameNS('*','RowInfo');
333 Roo.each(ci, function(c) {
334 var count = c.getAttribute('Count') || 1;
335 var s = c.getAttribute('No')*1;
336 for(var i =0; i < count; i++) {
337 _t.rowInfo[s+i] = Math.floor(c.getAttribute('Unit')*1);
348 * put the style info onto the cell data.
351 overlayStyles : function ()
355 Roo.each(this.styles, function(s) {
357 for (var r = s.r; r < s.r1;r++) {
358 if (typeof(_t.grid[r]) == 'undefined') {
361 for (var c = s.c; c < s.c1;c++) {
362 if (c > _t.cmax) continue;
364 if (typeof(_t.grid[r][c]) == 'undefined') _t.grid[r][c] = Roo.applyIf({ r: r , c : c }, _t.defaultCell);
366 if (typeof(g.cls) =='undefined') {
370 if (g.cls.indexOf(s.name) > -1) continue;
372 g.styles.push(s.dom);
380 * read the style information
381 * generates a stylesheet for the current file
382 * this should be disposed of really.....
385 parseStyles : function() {
387 var srs = this.sheet.getElementsByTagNameNS('*','StyleRegion');
392 HAlign : function(ent,v) {
393 ent['text-align'] = { '1' : 'left', '8': 'center', '4' : 'right'}[v] || 'left';
395 VAlign : function(ent,v) {
396 ent['vertical-align'] = { '1' : 'top', '4': 'middel', '8' : 'bottom'}[v] || 'top'
398 Fore : function(ent,v) {
400 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
401 ent['color'] = 'rgb(' + col.join(',') + ')';
403 Back : function(ent,v) {
405 Roo.each(v.split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
406 ent['background-color'] = 'rgb(' + col.join(',') + ')';
408 FontUnit : function(ent,v) {
409 ent['font-size'] = v + 'px';
411 FontBold : function(ent,v) {
413 ent['font-weight'] = 'bold';
415 FontItalic : function(ent,v) {
417 //ent['font-weight'] = 'bold';
419 FontName : function(ent,v) {
420 ent['font-family'] = v;
422 BorderStyle : function(ent,v) {
423 var vv = v.split('-');
424 ent['border-'+vv[0]+'-style'] = 'solid';
425 ent['border-'+vv[0]+'-width'] = vv[1]+'px';
427 BorderColor : function(ent,v) {
428 var vv = v.split('-');
430 Roo.each(vv[1].split(':'), function(c) { col.push(Math.round(parseInt(c,16)/256)); })
431 ent['border-'+vv[0]+'-color'] = 'rgb(' + col.join(',') + ')';
434 function add(e, k, v) {
437 if (typeof(map[k]) == 'undefined') {
447 Roo.each(srs, function(sr,n)
450 c : sr.getAttribute('startCol') *1,
451 r : sr.getAttribute('startRow')*1,
452 c1 : (sr.getAttribute('endCol')*1) +1,
453 r1 : (sr.getAttribute('endRow')*1) +1,
454 style : {}, // key val of style for HTML..
455 gstyle : {}, // key val of attributes used..
456 name : sid +'-gstyle-' + n,
461 Roo.each(sr.getElementsByTagNameNS('*','Style')[0].attributes, function(e) {
462 add(ent, e.name, e.value);
464 if (sr.getElementsByTagNameNS('*','Font').length) {
465 Roo.each(sr.getElementsByTagNameNS('*','Font')[0].attributes, function(e) {
466 add(ent, 'Font'+e.name, e.value);
469 add(ent, 'FontName', sr.getElementsByTagNameNS('*','Font')[0].textContent);
472 if (sr.getElementsByTagNameNS('*','StyleBorder').length) {
473 Roo.each(sr.getElementsByTagNameNS('*','StyleBorder')[0].childNodes, function(e) {
477 Roo.each(e.attributes, function(ea) {
478 add(ent, 'Border'+ea.name, e.tagName.split(':')[1].toLowerCase() + '-' + ea.value);
484 css['.'+ent.name] = ent.style;
487 this.styles = styles;
489 this.stylesheetID = sid;
490 Roo.util.CSS.createStyleSheet(css, sid);
493 /* --------------------------------------- AFTER LOAD METHODS... ----------------------- */
496 * Set the value of a cell..
497 * @param {String} cell name of cell, eg. C10 or { c: 1, r :1 }
499 * @param {Value} value to put in cell..
500 * @param {ValueType} type of value
501 * @param {ValueFormat} value format of cell
503 * Cells should exist at present, we do not make them up...
507 set : function(cell, v, vt, vf) {
509 var cs= typeof(cell) == 'string' ? this.toRC(cell) : cell;
510 //Roo.log( cs.r+ ',' + cs.c + ' = '+ v);
511 // need to generate clell if it doe
512 if (typeof(this.grid[cs.r]) == 'undefined') {
513 Roo.log('no row:' + cell);
514 this.grid[cs.r] = []; // create a row..
517 if (typeof(this.grid[cs.r][cs.c]) == 'undefined') {
518 Roo.log('cell not defined:' + cell);
519 this.createCell(cs.r,cs.c);
521 if (typeof(this.grid[cs.r][cs.c].dom) == 'undefined') {
522 Roo.log('no default content for cell:' + cell);
523 this.createCell(cs.r,cs.c);
526 this.grid[cs.r][cs.c].value= v;
527 this.grid[cs.r][cs.c].dom.textContent= v;
528 if (typeof(vt != 'undefined') && vt) {
529 this.grid[cs.r][cs.c].valueType = vt;
530 this.grid[cs.r][cs.c].dom.setAttribute('ValueType', vt);
532 if (typeof(vf != 'undefined') && vf) {
533 this.grid[cs.r][cs.c].valueFormat = vf;
534 this.grid[cs.r][cs.c].dom.setAttribute('ValueFormat', vf);
540 copyRow : function(src, dest) {
544 // Roo.log('create Row' + dest);
545 if (typeof(this.grid[dest]) == 'undefined') {
550 for (var c = 0; c < this.cmax; c++) {
552 this.copyCell({ r: src, c: c } , { r: dest, c: c});
555 this.rmax = Math.max(this.rmax, dest +1);
561 createCell: function(r,c)
563 //<gnm:Cell Row="6" Col="5" ValueType="60">Updated</gnm:Cell>
564 var nc = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:Cell');
565 this.cellholder.appendChild(nc);
566 var lb = this.doc.createTextNode("\n");// add a line break..
567 this.cellholder.appendChild(lb);
569 nc.setAttribute('Row', new String(r));
570 nc.setAttribute('Col', new String(c));
571 nc.setAttribute('ValueType', '60');
574 this.grid[r][c] = Roo.applyIf({
588 copyCell : function(src, dest)
590 var old = this.grid[src.r][src.c];
592 if ((old.c != src.c) || (old.r != src.r)) {
593 // only really works on horizonatal merges..
595 this.grid[dest.r][dest.c] = this.grid[desc.r][old.c]; // let's hope it exists.
600 var nc = Roo.apply({}, this.grid[src.r][src.c]);
603 if (typeof(old.dom) == 'undefined') {
604 Roo.log("No cell to copy for " + Roo.encode(src));
607 this.grid[dest.r][dest.c] = nc;
608 nc.dom = old.dom.cloneNode(true);
609 nc.dom.setAttribute('Row', dest.r);
610 nc.dom.setAttribute('Cell', dest.c);
611 nc.dom.textContent = '';
612 old.dom.parentNode.appendChild(nc.dom);
613 if (!old.styles || !old.styles.length) {
620 Roo.each(old.styles, function(s) {
621 // try and extend existing styles..
622 var er = s.getAttribute('endRow') * 1;
623 var ec = s.getAttribute('endCol') * 1;
626 s.setAttribute('endRow', dest.r + 1);
629 s.setAttribute('endCol', dest.c + 1);
631 /*var ns = s.cloneNode(true);
632 s.parentNode.appendChild(ns);
633 ns.setAttribute('startCol', dest.c);
634 ns.setAttribute('startRow', dest.r);
635 ns.setAttribute('endCol', dest.c + 1);
636 ns.setAttribute('endRow', dest.r +1);
645 * Set the value of a cell..
646 * @param {String} cell name of cell, eg. C10
647 * @param {Value} value to put in cell..
649 * Cells should exist at present, we do not make them up...
652 applyData : function(data)
655 data = data || this.data;
656 for (var r = 0; r < this.rmax;r++) {
657 if (typeof(this.grid[r]) == 'undefined') continue;
658 for (var c = 0; c < this.cmax;c++) {
659 if (typeof(this.grid[r][c]) == 'undefined') {
662 if (!this.grid[r][c].value.length
663 || !this.grid[r][c].value.match(/\{/)) {
667 var x = new Roo.Template({ html: this.grid[r][c].value });
669 var res = x.applyTemplate(data);
670 //Roo.log("set " + r + "," + c + ":"+res)
671 this.set({ r: r, c: c}, x.applyTemplate(data));
673 // Roo.log(e.toString());
685 * Import a table and put it into the spreadsheet
686 * @param {HTMLTable} datagrid dom element of html table.
687 * @param {Number} xoff X offset to start rendering to
688 * @param {Number} yoff Y offset to start rendering to
692 importTable : function (datagrid, xoff,yoff)
695 Roo.log("Error table not found!?");
701 var cleanHTML = function (str) {
704 ret = ret.replace(/ /g,'.');
705 ret = ret.replace(/\n/g,'.');
706 ret = ret.replace(/\r/g,'.');
708 while (-1 != (i = ret.indexOf(unescape('%A0')))) {
709 ret = ret.substring(0,i) + ' ' + ret.substring(i+1,str.length);
715 // <cell col="A" row="1">Test< / cell>
716 // <cell col="B" row="2" type="Number" format="test1">30< / cell>
718 var rows = datagrid.getElementsByTagName('tr');
719 //alert(rows.length);
721 for(var row=0;row<rows.length;row++) {
722 //var style = document.defaultView.getComputedStyle(rows[row], "");
724 //if (rows[row].getAttribute('xls:height')) {
725 // this.setRowHeight(row+y_offset, 0 + rows[row].getAttribute('xls:height'));
727 // this.setRowHeight(row+y_offset, 0 + style.height.replace(/[^0-9.]+/g,''));
731 // if (rowOffsets[row]) {
732 // coloffset += rowOffsets[row];
734 var cols = rows[row].getElementsByTagName('td');
737 for(var col=0;col < cols.length; col++) {
740 //var colat = col + coloffset;
742 if (cols[col].getAttribute('colspan') && (cols[col].getAttribute('colspan') > 1)) {
748 colat + (cols[col].getAttribute('colspan') - 1),
750 (cols[col].getAttribute('rowspan') > 1) ?
751 (cols[col].getAttribute('rowspan') - 1) : 0
757 coloffset += (cols[col].getAttribute('colspan') - 1);
760 if (cols[col].getAttribute('rowspan') && (cols[col].getAttribute('rowspan') > 1)) {
761 // this should really do a merge, but it's pretty damn complex...
762 //this.mergeRegion(colat,row +y_offset,colat + (cols[col].getAttribute('colspan') - 1), row+y_offset);
763 var rroff = cols[col].getAttribute('colspan') ? (cols[col].getAttribute('colspan') -0): 1;
765 for (rr = 0; rr < cols[col].getAttribute('rowspan');rr++) {
766 rowOffsets[rr + row] = col + rroff;
773 var style = this.newStyle();
774 if (style.setFrom(cols[col])) {
779 colat+x_offset + ((cols[col].getAttribute('colspan') > 1) ?
780 (cols[col].getAttribute('colspan') - 1) : 0),
781 row+y_offset + ((cols[col].getAttribute('rowspan') > 1) ?
782 (cols[col].getAttribute('rowspan') - 1) : 0)
788 if (!cols[col].childNodes.length) {
798 switch(cols[col].getAttribute('xls:type')) {
804 vt = 40; // float!!!!
805 if (cols[col].getAttribute('xls:floatformat')) {
806 vf = cols[col].getAttribute('xls:floatformat');
812 //ValueFormat="d/m/yyyy" 38635
814 if (cols[col].getAttribute('xls:dateformat')) {
815 vf= cols[col].getAttribute('xls:dateformat');
827 if (cols[col].getAttribute('xls:src')) {
828 //alert(cols[col].childNodes[0].width);
831 colat+x_offset+coloffset,
832 cols[col].getAttribute('xls:src'),
833 cols[col].childNodes[0].width,
834 cols[col].childNodes[0].height
842 if (!cols[col].childNodes[0].nodeValue) {
845 if (!cols[col].childNodes[0].nodeValue.replace(/^\s*|\s*$/g,"").length) {
849 var cell_value_text = cleanHTML(cols[col].childNodes[0].nodeValue);
851 if (cols[col].getAttribute('xls:percent')) {
852 cell_value_text = '' + ((cell_value_text * 1) / 100);
855 if (cell_value_text.length && (vt == 30)) {
856 var bits = cell_value_text.split(/-/);
857 var cur = new Date(bits[0],bits[1]-1,bits[2]);
858 cell_value_text = '' + Math.round((cur.getTime() - Date.UTC(1899,11,30)) / (24 * 60 * 60 * 1000));
863 if (cols[col].getAttribute('xls:formula')) {
864 var s = cols[col].getAttribute('xls:formula');
865 cols[col].removeAttribute('ValueType');
866 cell_value_text = s.replace(/#row#/g,(row + yoff + 1));
868 this.set({ r: row + yoff, c : col + xoff }, cell_value_text, vt, vf);
876 this.rowOffset += rows.length;
882 * Set the sheet name.
883 * @param {String} title for sheet
885 setSheetName : function(n)
889 <gnm:SheetName>Sheet1</gnm:SheetName>
890 <gnm:SheetName>Sheet2</gnm:SheetName>
891 <gnm:SheetName>Sheet3</gnm:SheetName>
892 </gnm:SheetNameIndex>
894 var sheetn = this.doc.getElementsByTagNameNS('*','SheetName')[0];
895 sheetn.textContent = n;
900 * Set the column width
901 * @param {Number} column number (starts at '0')
902 * @param {Number} width size of column
904 setColumnWidth : function(column, width)
908 if (typeof(this.colInfoDom[column]) == 'undefined') {
909 var cols = this.doc.getElementsByTagNameNS('*','Cols')[0];
910 var ri = this.doc.createElementNS('http://www.gnumeric.org/v10.dtd', 'gnm:ColInfo');
911 ri.setAttribute('No', column);
912 ri.setAttribute('Unit', width);
913 ri.setAttribute('MarginA', 2);
914 ri.setAttribute('MarginB', 2);
915 ri.setAttribute('HardSize', 1);
916 cols.appendChild(ri);
917 this.colInfo[column] = width;
918 this.colInfoDom[column] = ri;
921 this.colInfoDom[column].setAttribute('Unit', width);
926 * Convert spreadsheet into a HTML table.
932 function calcWidth(sc, span)
935 for(var i =sc; i< sc+span;i++) {
941 var grid = this.grid;
942 // lets do a basic dump..
943 var out = '<table style="table-layout:fixed;" cellpadding="0" cellspacing="0">';
944 for (var r = 0; r < this.rmax;r++) {
945 out += '<tr style="height:'+this.rowInfo[r]+'px;">';
946 for (var c = 0; c < this.cmax;c++) {
947 var g = (typeof(grid[r][c]) == 'undefined') ? defaultCell : grid[r][c];
949 if (typeof(g.cls) =='undefined') g.cls = [];
950 var w= calcWidth(c,g.colspan);
951 out+=String.format('<td colspan="{0}" rowspan="{1}" class="{4}"><div style="{3}">{2}</div></td>',
952 g.colspan, g.rowspan, g.value,
956 'text-overflow:ellipsis;' +
957 'white-space:nowrap;',
967 return out+'</table>';
974 * @param {String} name filename to downlaod (without xls)
975 * @param {String} callback (optional) - callback to call after callback is complete.
977 download : function(name,callback)
979 name = name || "Missing_download_filename";
981 if (this.downloadURL && this.downloadURL.charAt(this.downloadURL .length-1) != '/') {
982 this.downloadURL += '/';
985 var ser = new XMLSerializer();
986 var x = new Pman.Download({
989 xml : ser.serializeToString(this.doc),
990 format : 'xls', //xml
994 url : (this.downloadURL || (baseURL + '/GnumericToExcel/')) + name + '.xls',
995 success : function() {
996 Roo.MessageBox.alert("Alert", "File should have downloaded now");