【问题标题】:jQuery if excel cell value is negative, color text redjQuery如果excel单元格值为负,则将文本着色为红色
【发布时间】: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


【解决方案1】:

编辑:如果你只需要有一种红色字体值,那么你可以替换其中一种预设字体:

var styles = xlsx.xl['styles.xml'];
// change white font to red for negative numbers
$('fonts font:nth-child(2) color', styles).attr('rgb', 'FFFF0000');
// reference this font with $('c').attr('s', '1');

好的,所以我实际上设法完成了这项工作。您必须使用自定义字体/填充/边框值。这些值在“styles.xml”文件中可用。请看下面的代码:

            customize: function (xlsx) {
                // add in custom font for negative numbers
                var styles = xlsx.xl['styles.xml']
                $('fonts', styles).empty();
                $('fonts', styles).attr('count', '3');
                $('fonts', styles).append(`
                  <font>
                    <sz val="11"/>
                    <color rgb="00000000"/>
                    <name val="Calibri"/>
                    <family val="2"/>
                    <scheme val="minor"/>
                  </font>
                  <font>
                    <b/>
                    <sz val="11"/>
                    <color rgb="00000000"/>
                    <name val="Calibri"/>
                    <family val="2"/>
                    <scheme val="minor"/>
                  </font>
                  <font>
                    <sz val="11"/>
                    <color rgb="FFFF0000"/>
                    <name val="Calibri"/>
                    <family val="2"/>
                    <scheme val="minor"/>
                  </font>
                `);
                $('fills', styles).empty();
                $('fills', styles).attr('count', '2');
                $('fills', styles).append(`
                <fill>
                  <patternFill patternType="none"/>
                </fill>
                <fill>
                  <patternFill patternType="gray125"/>
                </fill>
                `);
                $('borders', styles).empty();
                $('borders', styles).attr('count', '1');
                $('borders', styles).append(`
                <border>
                  <left/>
                  <right/>
                  <top/>
                  <bottom/>
                  <diagonal/>
                </border>
                `);
                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', '1');}
                  // highlight red all rows that start with - (negative numbers)
                  $('c', this).each(function() {
                    if ($('v', this).text().startsWith('-')) {
                        console.log($('v', this).text());
                        $(this).attr('s', '2');
                    }
                  });
                });
            }

这里我去掉了默认字体、填充和边框。我添加了三种字体,标准黑色字体、加粗黑色字体和红色字体。

我还添加了标准填充和边框。

然后我可以使用“s”属性来引用这些。基础价值只是不同。

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2013-09-01
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多