2015-04-17 19 views
21

Come posso convertire più tabelle html in un foglio Excel con più fogli di lavoro? Potresti per favore aiutare in questo.Come convertire la tabella html in Excel con fogli multipli?

Il mio esempio https://jsfiddle.net/kdkd/5p22gdag/

 function tablesToExcel() { 
     { 

      var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>"; 
      var textRange; var j = 0; 
      tab = document.getElementById('tbl2'); // id of table 


      for (j = 0 ; j < tab.rows.length ; j++) { 
       tab_text = tab_text + tab.rows[j].innerHTML + "</tr>"; 
       //tab_text=tab_text+"</tr>"; 
      } 

      tab_text = tab_text + "</table>"; 
      var ua = window.navigator.userAgent; 
      var msie = ua.indexOf("MSIE "); 

      if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer 
      { 
       txtArea1.document.open("txt/html", "replace"); 
       txtArea1.document.write(tab_text); 
       txtArea1.document.close(); 
       txtArea1.focus(); 
       sa = txtArea1.document.execCommand("SaveAs", true, "Say Thanks to Sumit.xls"); 
      } 
      else     //other browser not tested on IE 11 
       sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); 


      return (sa); 
     } 

} 
+0

Sono state prese queste domande: http://stackoverflow.com/questions/24636956/how-do-i- export-multiple-html-tables-to-excel e http://stackoverflow.com/questions/18234448/exporting-html-tables-to-excel-xls-in-a-separate-sheet? sembrano avere soluzioni per questo –

+0

Grazie per quello. Ho controllato il collegamento sopra indicato. Un piccolo problema è che tutta la tabella HTML è stata inserita in un foglio di lavoro. (Foglio di lavoro multipla creato con successo) ma, –

+0

Ecco un esempio di ciò che si desidera..http: //jsfiddle.net/qxLn3h86/ –

risposta

33

Si può fare di seguito: Here is Full Example

Html:

<table id="tbl1" class="table2excel"> 
     <tr> 
      <td>Product</td> 
      <td>Price</td> 
      <td>Available</td> 
      <td>Count</td> 
     </tr> 
     <tr> 
      <td>Bred</td> 
      <td>1</td> 
      <td>2</td> 
      <td>3</td> 
     </tr> 
     <tr> 
      <td>Butter</td> 
      <td>4 </td> 
      <td>5 </td> 
      <td >6 </td> 
     </tr> 
    </table> 
<hr> 

    <table id="tbl2" class="table2excel"> 
     <tr> 
      <td>Product</td> 
      <td>Price</td> 
      <td>Available</td> 
      <td>Count</td> 
     </tr> 
     <tr> 
      <td>Bred</td> 
      <td>7</td> 
      <td>8</td> 
      <td>9</td> 
     </tr> 
     <tr> 
      <td>Butter</td> 
      <td>14</td> 
      <td>15</td> 
      <td >16</td> 
     </tr> 
    </table> 


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

Javascript:

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>Axel Richter</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); 



     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); 
    } 
    })(); 
+3

questo è puro genio! :-) –

+0

Ho provato questo, ma il mio tavolo ha inline CSS quindi non funziona. Per favore controlla questo fiddle http://jsfiddle.net/kdkd/qxLn3h86/49/ –

+0

Questo link potrebbe esserti d'aiuto .http: //stackoverflow.com/questions/18467418/retain-html-table-styling-after-exporting- to-excel-using-javascript-jquery –

-1
function tablesToExcel() { 
     { 

      var tab_text = document.getElementById("MsoNormalTable").outerHTML; 
      var textRange; var j = 0; 
      var tab = document.getElementById('MsoNormalTable'); // id of table 
      var sa; 

      var ua = window.navigator.userAgent; 
      var msie = ua.indexOf("MSIE "); 
      var txt = document.getElementById('txtArea1').contentWindow; 
      if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer 
      { 
       txt.document.open("txt/html", "replace"); 
       txt.document.write(tab_text); 
       txt.document.close(); 
       txt.focus(); 
       sa = txt.document.execCommand("SaveAs", true, "Say Thanks to Sumit.xls"); 
      } 
      else     //other browser not tested on IE 11 
       sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); 

      return (sa); 
     } 
} 

<iframe id="txtArea1" style="display:none"></iframe> 

Si sta lavorando con IE7 + fine ... :)

+0

funziona con più fogli? No! irrilevante qui. – Suncatcher

2

Here è una soluzione migliore che supporta tavolo esportatore nella più recente formato Excel cioè xlsx . La soluzione accettata fallirebbe nel caso in cui il numero totale di righe da esportare fosse superiore a 3407 su Chrome.

Un esempio dal link qui sopra: http://jsfiddle.net/6ckj281f/

html

<button onclick="saveFile()">Save XLSX file</button> 

javascript

window.saveFile = function saveFile() { 
var data1 = [{a:1,b:10},{a:2,b:20}]; 
var data2 = [{a:100,b:10},{a:200,b:20}]; 
var opts = [{sheetid:'One',header:true},{sheetid:'Two',header:false}]; 
var res = alasql('SELECT INTO XLSX("restest344b.xlsx",?) FROM ?', 
       [opts,[data1,data2]]); 
} 
+0

Oh questo è esattamente quello che stavo cercando. Grazie! – crashtestxxx

0

codice di Bhutani Vijay funziona perfettamente bene. Per IE 11 compatibilità ho usato l'oggetto Blob, come di seguito:

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>Axel Richter</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); 
 

 
    var link = document.createElement("A"); 
 
    
 
    // IE 11 
 
    if (window.navigator.msSaveBlob) { 
 
     var blob = new Blob([workbookXML], { 
 
     type: "application/csv;charset=utf-8;" 
 
     }); 
 
     navigator.msSaveBlob(blob, 'test.xls'); 
 
    } 
 
    // Chrome and other browsers 
 
    else { 
 
     link.href = uri + base64(workbookXML); 
 
    } 
 

 
    link.download = wbname || 'Workbook.xls'; 
 
    link.target = '_blank'; 
 
    document.body.appendChild(link); 
 
    link.click(); 
 
    document.body.removeChild(link); 
 
    } 
 
})();

Problemi correlati