Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript将工作表添加到excel文件_Javascript_Excel - Fatal编程技术网

使用javascript将工作表添加到excel文件

使用javascript将工作表添加到excel文件,javascript,excel,Javascript,Excel,假设我有3张桌子。我想将3个工作表中的表(每页一个表)插入到单个excel文件中(不需要ActiveXObject) 我尝试了以下代码,但它只创建了一个工作表 var tableToExcel = (function () { var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" x

假设我有3张桌子。我想将3个工作表中的表(每页一个表)插入到单个excel文件中(不需要ActiveXObject)

我尝试了以下代码,但它只创建了一个工作表

var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table><table>{table}</table></body></html>',
        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 (table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        }
        window.location.href = uri + base64(format(template, ctx))
    }
})();
var tableToExcel=(函数(){
var uri='data:application/vnd.ms excel;base64',
模板=“{table}{table}”,
base64=函数{
返回窗口.btoa(unescape(一个或多个组件)))
},格式=函数(s,c){
返回s.replace(/{(\w+)}/g,函数(m,p){
返回c[p];
})
}
返回函数(表、名称){
如果(!table.nodeType)table=document.getElementById(table)
变量ctx={
工作表:名称| |‘工作表’,
表:table.innerHTML
}
window.location.href=uri+base64(格式(模板,ctx))
}
})();

您展示的方法混合使用了电子表格XML和HTML。使用这种混合物,不可能填充多张工作表。为此,我们必须只使用电子表格XML。这是因为只有XML可以描述多个工作表。HTML表格数据与除活动工作表之外的任何工作表都不相关

只使用电子表格XML是可能的,但是我们必须仔细处理数据类型。如果Excel导入HTML,它会尝试检测数据类型,就像用户将值手动输入单元格一样。对于XML,情况并非如此。它从XML中获取给定的数据类型。如果它们不匹配,则会产生错误。因此,在我的示例中,我使用“data-”attríbutes来描述数据类型、数据样式和数据值。因此,在HTML表格单元(TD)中,数据值可能与数据表示不同。因为HTML是一种数据表示格式,而不是数据交换格式,所以我认为这也是一种很好的做法

有关电子表格XML,请参见:

该示例使用数据URI作为下载链接,因此它仅适用于支持此功能的浏览器。它不能与Microsoft Internet Explorer一起使用

例如:

<script type="text/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);

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);
    }
  })();
</script> 

<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>

var tablesToExcel=(函数(){
var uri='data:application/vnd.ms excel;base64,'
,tmplWorkbookXML=“”
+"

问候


Axel

您不能对多个工作表使用这种方法。感谢您的回复。是否有添加工作表的想法,因为这对我来说是一个紧急要求。我需要解决这种情况的任何解决方案。我将相同的代码复制到xhtml(JSF 2.2)中,然后我得到下一个错误“不允许处理指令目标匹配”[xX][mM][lL]”。我在互联网上查看过,但没有找到解决方案。如果有人能帮助我,我将不胜感激。该脚本是纯JavaScript,必须在浏览器中运行。JSFIDLE适用于我的Firefox浏览器。不知道你在使用JSF 2.2做什么。虽然它工作正常,但无法检测colspan和rowspans@Saeed贾萨尼:这种方法很简单过时了。我不会再为这个困扰自己了。在野外有JavaScript库,可以真正创建Excel文件。例如。谢谢你的参考。我将尝试一下