You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT报表中实现列值变化时交替行颜色?

实现XSLT报表中值变化时切换行颜色

我明白你要的是那种相同值的行同色,值一变就切换颜色的报表效果,之前我做类似需求的时候,一开始也纠结分组没成功,后来发现用相邻值对比或者组序号判断就能搞定,给你两种可行的方案:

假设你的XML结构参考

先假设你的数据源大概是这样的(可以根据实际结构调整节点名):

<report>
  <row>
    <id>1</id>
    <value>123</value>
  </row>
  <row>
    <id>2</id>
    <value>123</value>
  </row>
  <row>
    <id>3</id>
    <value>876</value>
  </row>
  <row>
    <id>4</id>
    <value>848</value>
  </row>
  <row>
    <id>5</id>
    <value>543</value>
  </row>
  <row>
    <id>6</id>
    <value>543</value>
  </row>
  <row>
    <id>7</id>
    <value>543</value>
  </row>
</report>

方案1:XSLT 1.0 兼容写法(无需分组)

如果你的环境只能用XSLT 1.0,可以通过统计当前行之前有多少个不同值的行,得到当前值所在的组序号,再用奇偶性判断颜色:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/report">
    <table border="1">
      <xsl:apply-templates select="row"/>
    </table>
  </xsl:template>

  <xsl:template match="row">
    <!-- 计算当前值所在的组序号:统计之前所有值不同的行数量 +1 -->
    <xsl:variable name="group-number" select="count(preceding-sibling::row[value != current()/value]) + 1"/>
    
    <!-- 奇偶组切换颜色:奇数组白,偶数组灰 -->
    <tr>
      <xsl:attribute name="bgcolor">
        <xsl:choose>
          <xsl:when test="$group-number mod 2 = 1">#FFFFFF</xsl:when>
          <xsl:otherwise>#E0E0E0</xsl:otherwise>
        </xsl:choose>
      </xsl:attribute>
      <td><xsl:value-of select="id"/></td>
      <td><xsl:value-of select="value"/></td>
    </tr>
  </xsl:template>
</xsl:stylesheet>

方案2:XSLT 2.0+ 分组写法(更直观)

如果你的环境支持XSLT 2.0或更高版本,用for-each-group分组会更清晰直接,按目标列的值分组后,给每个组分配一个位置序号,再根据序号奇偶设置颜色:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/report">
    <table border="1">
      <!-- 按value列的值分组 -->
      <xsl:for-each-group select="row" group-by="value">
        <!-- 获取当前组的序号 -->
        <xsl:variable name="group-index" select="position()"/>
        
        <!-- 遍历组内所有行,统一设置颜色 -->
        <xsl:for-each select="current-group()">
          <tr>
            <xsl:attribute name="bgcolor">
              <xsl:choose>
                <xsl:when test="$group-index mod 2 = 1">#FFFFFF</xsl:when>
                <xsl:otherwise>#E0E0E0</xsl:otherwise>
              </xsl:choose>
            </xsl:attribute>
            <td><xsl:value-of select="id"/></td>
            <td><xsl:value-of select="value"/></td>
          </tr>
        </xsl:for-each>
      </xsl:for-each-group>
    </table>
  </xsl:template>
</xsl:stylesheet>

注意事项

  • 把代码中的value替换成你实际用来判断的列节点名即可;
  • 颜色可以用颜色名称(比如white、lightgray)或者十六进制值,根据需求调整;
  • 方案1的思路是通过兄弟节点对比来模拟分组,不用显式分组,适合1.0环境;方案2是标准的分组写法,代码更易读维护。

内容的提问来源于stack exchange,提问作者Keijo Hotti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:45:50