首页 > 解决方案 > 导出的 Excel 文件中的自定义样式

问题描述

我正在尝试使用自定义样式从 Datatable 导出 excel 文件。我想让第一行背景颜色为蓝色,字体颜色为白色。下面的代码使背景颜色为蓝色,但未应用字体颜色为白色。

function(xlsx) {
                                             
  var styles = xlsx.xl['styles.xml'];
  
  f1 = '<font><sz val=\"12\" /><name val=\"Calibri\"/><color rgb=\"ffffff\"/></font>';
  s1 = '<fill><patternFill patternType=\"solid\"><fgColor rgb=\"213e82\" /></patternFill></fill>';
  s2 = '<xf numFmtId=\"168\" fontId=\"0\" fillId=\"6\" borderId=\"1\" applyFont=\"1\" applyFill=\"1\" applyBorder=\"1\" xfId=\"0\" applyAlignment=\"1\"><alignment horizontal=\"center\"/></xf>';

  styles.childNodes[0].childNodes[1].innerHTML += f1;
  styles.childNodes[0].childNodes[2].innerHTML += s1 + f1;
  styles.childNodes[0].childNodes[5].innerHTML += s2;

             var sheet = xlsx.xl.worksheets['sheet1.xml'];
             
             // first row
             $('row:eq(0) c', sheet).attr( 's', 67);

            //row with totals
            $('row:eq(-1) c', sheet).attr( 's', '2' );  //bold
            
    }

标签: xmldatatables

解决方案


在您的<xf>标签定义中,在变量s2中,将字体 ID 索引从 0 更改为 1: fontId="1"

然后它将引用您新添加的字体f1。当然,这假设您最终在样式表中使用了 2 种字体。如果有更多,您可能需要调整索引。

更新 - 边界:

这是样式表中的示例边框条目,在该<borders>部分中:

<border diagonalUp="false" diagonalDown="false">
    <left style="thin">
        <color auto="1"/>
    </left>
    <right style="thin">
        <color auto="1"/>
    </right>
    <top style="thin">
        <color auto="1"/>
    </top>
    <bottom style="thin">
        <color auto="1"/>
    </bottom>
    <diagonal/>
</border>

更新 2 - 控制导出的行和列

您可以使用该exportOptions功能来处理仅从第 2 行和第 2 列开始的数据导出:

    exportOptions: {
        rows: function ( idx, data, node ) {
            if (idx > 0) {
              return data;
            }
        },
        columns: function ( idx, data, node ) {
            if (idx > 0) {
              return data;
            }
          }
    },

    customize: function ( xlsx ) { ...},

这需要嵌套在与现有customize部分相同的级别。它使用一个函数来检查每一行和每一列的索引。

实际上还有另一种更短的方法可以做到这一点,您可以在其中明确列出所需的行索引和列索引:

exportOptions: {
  rows: [ 1, 2, 3, 4, 5 ],
  columns: [ 1, 2, 3, 4, 5 ]
}

但既然你想要“一切到最后”,功能就更好了。


推荐阅读