【问题标题】:Exporting to Excel with Color, Style使用颜色、样式导出到 Excel
【发布时间】:2020-09-04 18:49:04
【问题描述】:

我有两个脚本,一个成功地将行和列的颜色和样式导出到 xlsx,其中包含类和行 css。我有一个更复杂的脚本,可以导出多个工作表,我想对其应用样式。但是,第二个不起作用。我觉得问题在于 javascript,尤其是模板部分,否则我看不出有什么区别。这是一个有效的方法:

    <script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var tableToExcel = (function () {
        // Define your style class template.
        var style = "<style>.green { background-color: green; }</style>";
        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]-->' + style + '</head><body><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))
        }
    })()
</script>
<style type="text/css">
    .green
    {
        background-color: green;
    }
</style>
    <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table', 'testTable2', 'This is a test')" value="Export to Excel" />
    <table id="testTable" summary="Code page support in different versions of MS Windows."
        rules="groups" frame="hsides" border="2">
    <caption>
        CODE-PAGE SUPPORT IN MICROSOFT WINDOWS
    </caption>
    <colgroup align="center"></colgroup>
    <colgroup align="left"></colgroup>
    <colgroup span="2" align="center"></colgroup>
    <colgroup span="3" align="center"></colgroup>
    <thead valign="top">
        <tr>
            <th>Code-Page<br />ID</th>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Windows<br />NT 3.1</th>
            <th>Windows<br />NT 3.51</th>
            <th>Windows<br />95</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1200</td>
            <td style="background-color: #00f; color: #fff">Unicode (BMP of ISO/IEC-10646)</td>
            <td></td>
            <td></td>
            <td>X</td>
            <td>X</td>
            <td>*</td>
        </tr>

这是一个没有错误的脚本,只是不会在相同的 html 元素上发布样式:

头:

<script>
      var tablesToExcel = (function() {
    var style = "<style>.green { background-color: green; }</style>";       
    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>Seecuring</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 || 'Oracle Cloud Snapshot Management.xls';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);




    }
  })();







</script>   
    <style type="text/css">
    .green
    {
        background-color: #0F51F6;
    }
</style>
  </head>

html:

   <table id="intro" class="table2excel" rules="groups" frame="hsides" border="2">
                    <tr>
                        <td><!--<img src='<?php //echo $environment; ?>/access/images/erpra.png' width='100px' height='100px'> --></td>

                    </tr>
                    <tr>
                        <td class="green">KPMG - Oracle Cloud ERP/HCM Configuration Management Assessment
                        <td>
</td>
                        <td>
</td>
                        <td>
</td>
                    </tr>
                    <tr>
                        <td style="background-color: #00f; color: #fff">A review of key Configuration elements within the Oracle Cloud Applications/Fusion suite. <?php if(!isset($_POST['no_date'])&& $_POST['no_date']== "Y"){
                        $CREATION_DATE_POST_DISPLAY_RAW = $_POST['creation_from'];
  $CREATION_DATE_DISPLAY=date("m/d/Y",strtotime($CREATION_DATE_POST_DISPLAY_RAW));

  $LAST_UPDATE_DATE_POST_DISPLAY_RAW = $_POST['update_from'];
   $LAST_UPDATE_DATE_DISPLAY=date("m/d/Y",strtotime($LAST_UPDATE_DATE_POST_DISPLAY_RAW));
   echo "Creation Date from : $CREATION_DATE_DISPLAY, Last Updated Date from: $LAST_UPDATE_DATE_DISPLAY";

                        }
   ?></td>

感谢阅读!

【问题讨论】:

    标签: javascript excel html-table


    【解决方案1】:
    <div>
        <style>
            @media all {
                .page-break {
                    display: none;
                }
            }
    
            @media print {
                .page-break {
                    display: block;
                    page-break-inside: auto;
                }
            }
        </style>
    </div>
    

    【讨论】:

    • 您好,欢迎来到 Stack Overflow!请拨打tour。感谢您提供答案,但您能否添加关于您的代码如何解决问题的说明?
    猜你喜欢
    • 1970-01-01
    • 2019-04-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多