【发布时间】:2021-02-17 06:40:00
【问题描述】:
我正在使用 Datatables 库来呈现 HTML 表格,然后单击按钮输出一个 Excel 文档。这是我目前拥有的代码:
$(document).ready( function () {
$('#mainTable').DataTable({
fixedHeader: false,
dom: 'Bfrtip',
buttons: [
{
extend: 'copy',
exportOptions: {
columns: ':not(:first-child)',
rows: ':visible'
}
},
{
extend: 'excelHtml5',
title: 'Profit and Loss Report',
messageTop: `Ran on ${(new Date()).toLocaleString()} for period <xsl:value-of select="P_PERIOD_NUM"/> - FY<xsl:value-of select="P_PERIOD_YEAR"/>`,
messageBottom: `Companies: <xsl:value-of select="P_COMP_CHILD"/> Cost Centers: <xsl:value-of select="P_CC_CHILD_1"/><xsl:value-of select="P_CC_CHILD_2"/>`,
// Function iterates over each row and applies styling if conditions are met
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
var rows = $('row:gt(2)', sheet);
rows.each(function () {
// bold all rows where first cell ends with : (totals, % or revs)
if ($('c:first-of-type is t', this).text().endsWith(':')) {$('c', this).attr('s', '2');}
// highlight red all rows that start with - (negative numbers)
$('c', this).each(function() {
if ($('v', this).text().startsWith('-')) {
$(this).attr('s', '11');
}
});
});
}
},
{
extend: 'pdfHtml5',
title: 'Profit and Loss Report',
orientation: 'landscape',
pageSize: 'LEGAL',
messageTop: `Ran on ${(new Date()).toLocaleString()} for period <xsl:value-of select="P_PERIOD_NUM"/> - FY<xsl:value-of select="P_PERIOD_YEAR"/>`,
messageBottom: `Companies: <xsl:value-of select="P_COMP_CHILD"/> Cost Centers: <xsl:value-of select="P_CC_CHILD_1"/><xsl:value-of select="P_CC_CHILD_2"/>`
}
],
"ordering": false,
paging: false
});
如您所见,我有一个函数可以遍历 excel 文件的每一行。第一个 if 语句在第一个单元格字符串的末尾查找 ':'。求和行使用此字符,因此它们是粗体的。
但是,我遇到的问题是这段代码:
if ($('v', this).text().startsWith('-')) {
$(this).attr('s', '11');
}
if 语句按预期工作;它选择以 - (负数)开头的每个单元格。 if 语句的主体是问题所在。我想用红色字体来显示负数。值为“11”的属性“s”表示白色文本和红色背景。这和我所得到的一样接近。我找不到任何实际上只是将文本设置为红色的东西。
编辑:我在这里找到了 excel s 属性的值列表,以防万一有用:https://datatables.net/reference/button/excelHtml5
【问题讨论】:
-
@RoryMcCrossan 我设法将字体更改为适当的颜色。我为您在下面看到的问题添加了自己的答案。我必须做的是用我自己的自定义值覆盖默认字体/填充/边框。然后我可以像正常一样使用“s”属性来引用这些。
-
很高兴被证明是错误的 :) 很高兴你让它工作了 - 尽管由于 Excel 格式绝对是一场噩梦,那是一些该死的丑陋代码。
标签: jquery excel xml datatables