xml - 导出的 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
}
解决方案
在您的<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 ]
}
但既然你想要“一切到最后”,功能就更好了。
推荐阅读
- javascript - 制作不同大小的魔方
- android - 我应该在paypal check android sdk的用户名和密码字段中输入什么?
- pyspark - 如何在 pyspark 中进行一种热编码
- c# - WCF Webservice 使用 Stream 传递 messagecontract 并将字符串返回给客户端
- blockchain - OS X 中外部 SSD 上的比特币核心
- python - 动态检索包目录的绝对路径
- firebase - 非谷歌服务器上的 Firebase 云功能
- typescript - 升级到 typescript 4.4.2 后如何修复“错误‘JSX’未定义 no-undef’
- user-interface - 为什么像 SwiftUI 或 Flutter/Dart 或 Compose/Kotlin 这样的 UI 系统使用声明式方法而不是命令式方法来定义 GUI?
- next.js - 如果所有代码看起来都正确,我该如何解决“Lighthouse 无法下载 robots.txt 文件”?