在几个工作表中将HTML表导出为Excel

时间:2015-01-23 15:48:02

标签: javascript excel export

我必须在一些工作表中将一些表导出到excel。

我在这个主题上使用了Axel的代码:Adding worksheet to the excel file using javascript

一切似乎都很好,但出口没有开始;浏览器控制台显示XML日志,我不知道如何解决这个问题。

我认为这个问题与HTML表有关。有人知道这个问题吗?

Here are a test for Axel's code

以下是他的表:

<table id="tbl1">
  <tr>
    <td>Name</td>
    <td>Birthday</td>
    <td>Amount</td>
    <td>Rebate (10%)</td>
  </tr>
  <tr>
    <td>Smith</td>
    <td data-type="DateTime" data-style="Date" data-value="1980-03-23">Mar 23 1980</td>
    <td data-type="Number" data-style="Currency" data-value="1234.56">$ 1,234.56</td>
    <td data-formula="=RC[-1]/10" data-type="Number" data-style="Currency">$ 123.45</td>
  </tr>
  <tr>
    <td>Doe</td>
    <td data-type="DateTime" data-style="Date" data-value="1978-11-05">Nov 05 1978</td>
    <td data-type="Number" data-style="Currency" data-value="2345.67">$ 2,345.67</td>
    <td data-formula="=RC[-1]/10" data-type="Number" data-style="Currency">$ 234.56</td>
  </tr>
</table>
<hr>
<table id="tbl2">
  <tr>
    <td>Product</td>
    <td>Price</td>
    <td>Available</td>
    <td>Count</td>
  </tr>
  <tr>
    <td>Bred</td>
    <td data-type="Number" data-style="Currency" data-value="1.89">$ 1.89</td>
    <td data-type="Boolean" data-value="1">yes</td>
    <td data-type="Number" data-value="123">123</td>
  </tr>
  <tr>
    <td>Butter</td>
    <td data-type="Number" data-style="Currency" data-value=".89">$ .89</td>
    <td data-type="Boolean" data-value="0">no</td>
    <td data-type="Number" data-value="0">0</td>
  </tr>
</table>


<button  onclick="tablesToExcel(['tbl1','tbl2'], ['Customers','Products'], 'TestBook.xls', 'Excel')">Export to Excel</button>
<button  onclick="tablesToExcel(['tbl1','tbl2'], ['Customers','Products'], 'TestBook.xls', 'Calc')">Export to Calc</button>

以下是构建HTML表格的代码摘录:

for(var j=0;j<nbData;j++){
if(j==0){
    /*Gerer le premier affichage (Entete tableau)*/
    affData += "<BR/><center><table id=\"tableToExport_"+i+"\" class=\"donnees\"><tr class=\"titre\"><td>"+xmlDoc.getElementsByTagName("data")[j].childNodes[0].firstChild.nodeValue+"</td><td></td></tr>"
}
var date = xmlDoc.getElementsByTagName("data")[j].childNodes[1].firstChild.nodeValue;
var val = xmlDoc.getElementsByTagName("data")[j].childNodes[2].firstChild.nodeValue;
affData += "<tr>";
    affData += '<td data-type="DateTime" data-style="Date" data-value="'+date.substring(0,date.length-7)+'">'+date.substring(0,date.length-7)+'</td>';
    //affData += '<td data-type="DateTime" data-style="Date" data-value="'+date.substring(0,date.length-16)+'">'+date.substring(0,date.length-16)+'</td>';
    affData += '<td data-type="Number">'+val+"</td>";
affData += "</tr>";
if(j==nbData-1){
    /*Gerer le dernier affichage (Fermer tableau)*/
    affData += "</table></center><BR/>";
}

}

这是要导出的表格之一:

<table id="tableToExport_0">
<tbody>
  <tr class="titre">
    <td>Title</td>
    <td></td>
  </tr>
  <tr>
    <td data-type="DateTime" data-style="Date" data-value="2015-01-21 00:03:59">2015-01-21 00:03:59</td>
    <td data-type="Number">71.0</td>
  </tr>
  <tr>
    <td data-type="DateTime" data-style="Date" data-value="2015-01-21 00:09:00">2015-01-21 00:09:00</td>
    <td data-type="Number">72.0</td>
  </tr>
  <tr>
    <td data-type="DateTime" data-style="Date" data-value="2015-01-21 00:14:00">2015-01-21 00:14:00</td>
    <td data-type="Number">65.0</td>
  </tr>
  <tr>
    <td data-type="DateTime" data-style="Date" data-value="2015-01-21 00:19:00">2015-01-21 00:19:00</td>
    <td data-type="Number">75.0</td>
  </tr>
</tbody>
</table>

拜托,怎么了?

[编辑] 这是我的完整代码:

dialog = $( "#dialog-form" ).dialog({
	autoOpen: false,
	height:  400,
	width: 500,
	modal: true,
	buttons: {
		"Export to Excel": function() {
			var test=true;
			var valeurI = 0;
			var tables = new Array();
			var wsName = new Array();
			for(var i=0;test;i++){
				var tab = document.getElementById("tableToExport_"+i)
				if(tab==null){
					test = false;
					valeurI = i;
				}else{
					tables.push('tableToExport_'+i);
					wsName.push('Worksheet_'+i);
				}
			}
			//tablesToExcel(['tableToExport_0','tableToExport_1'], ['Customers','Products'], 'TestBook.xls', 'Excel');
			tablesToExcel(tables, wsName, 'DataReport.xls', 'Excel');
			//exportToExcel();
			//alert( "Export_"+getTimeDataReport());
			},
		"Cancel": function() {
			$( this ).dialog( "close" );
			},	
	},
	close: function(){}
});

var tablesToExcel = (function() {
	var uri = 'data:application/vnd.ms-excel;base64,'
   		, tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
	     	+ '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Benjamin BACKX</Author><Created>{created}</Created></DocumentProperties>'
	     	+ '<Styles>'
	    	+ '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
	    	+ '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
	   		+ '</Styles>' 
	     	+ '{worksheets}</Workbook>'
   		, tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
   		, tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
   		, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
   		, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
   return function(tables, wsnames, wbname, appname) {
   	 var ctx = "";
     var workbookXML = "";
     var worksheetsXML = "";
     var rowsXML = "";

     for (var i = 0; i < tables.length; i++) {
       if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
       for (var j = 0; j < tables[i].rows.length; j++) {
         rowsXML += '<Row>'
         for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
           var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
           var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
           var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
           dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
           var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
           dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
           ctx = {  attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
                  , nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
                  , data: (dataFormula)?'':dataValue
                  , attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
                 };
           rowsXML += format(tmplCellXML, ctx);
         }
         rowsXML += '</Row>'
       }
       ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
       worksheetsXML += format(tmplWorksheetXML, ctx);
       rowsXML = "";
     }

     ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
     workbookXML = format(tmplWorkbookXML, ctx);

console.log(workbookXML);

     var link = document.createElement("A");
     link.href = uri + base64(workbookXML);
     link.download = wbname || 'Workbook.xls';
     link.target = '_blank';
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
   }
 })();

function getTimeDataReport() {
	var today=new Date();
	var h=today.getHours();
	var m=today.getMinutes();
	var ddd=today.getDate()+'';
	var mmm=today.getMonth()+1+'';
	var yyy=today.getFullYear()+'';
	var dateToReturn = yyy+mmm+ddd+'_'+h+m;
	return dateToReturn;
}

function afficherData(plant, dateDebut, dateFin, domain, equipement, tableHiddenCB, dataType){

	
 	var action = "AFFICHER_DATAS";
	var affData = "";
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if(xhr.readyState==4 && xhr.status==200){
			var xmlDoc = xhr.responseXML;
		    var lenghtXml = xmlDoc.getElementsByTagName("objDesc").length;
				for(var i=0;i<lenghtXml;i++){
					var nbData = xmlDoc.getElementsByTagName("objDesc")[i].childNodes.length;
					for(var j=0;j<nbData;j++){
						if(j==0){
							/*Gerer le premier affichage (Entete tableau)*/
							affData += "<BR/><center><table id=\"tableToExport_"+i+"\" class=\"donnees\"><tr class=\"titre\"><td>"+xmlDoc.getElementsByTagName("data")[j].childNodes[0].firstChild.nodeValue+"</td><td></td></tr>"
						}
						var date = xmlDoc.getElementsByTagName("data")[j].childNodes[1].firstChild.nodeValue;
						var val = xmlDoc.getElementsByTagName("data")[j].childNodes[2].firstChild.nodeValue;
						affData += "<tr>";
							affData += '<td data-type="DateTime" data-style="Date" data-value="'+date.substring(0,date.length-7)+'">'+date.substring(0,date.length-7)+'</td>';
							//affData += '<td data-type="DateTime" data-style="Date" data-value="'+date.substring(0,date.length-16)+'">'+date.substring(0,date.length-16)+'</td>';
							affData += '<td data-type="Number">'+val+"</td>";
						affData += "</tr>";
						if(j==nbData-1){
							/*Gerer le dernier affichage (Fermer tableau)*/
							affData += "</table></center><BR/>";
						}
					}
				}
			affData += "";
			$("#dialog-form").html(affData);
			dialog.dialog( "open" );
		}							 
	}
	xhr.open("POST", "../Servlet",true);
   	xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');
   	xhr.send("...parameters...");
}

0 个答案:

没有答案