根据单元格中的数字自动更改单元格颜色

根据单元格中的数字自动更改单元格颜色

我想修改此代码以根据单元格中的数字自动更改单元格颜色而不是字体颜色。

\documentclass{article}
\usepackage{xcolor}
\usepackage{pgf}
\usepackage{collcell}
\usepackage{adjustbox}
\usepackage{multirow} 
\usepackage{pdflscape} 
\usepackage{booktabs}
\usepackage{colortbl}

% This selects the amount of color to use
\newcommand*{\MinNumber}{0}%
\newcommand*{\MaxNumber}{100}%

\newcommand{\ApplyGradient}[1]{
    \pgfmathsetmacro{\PercentColor}{100.0*(#1-\MinNumber)/(\MaxNumber-\MinNumber)}
    \textcolor{black!\PercentColor}{#1}
}
\newcolumntype{R}{>{\collectcell\ApplyGradient}{r}<{\endcollectcell}}

\begin{document}

\begin{table}{
\begin{tabular}{ c R R R R R R R R}
\toprule
\multicolumn{1}{c} {Tools} &
\multicolumn{1}{c} {D1} &
\multicolumn{1}{c} {D2} &
\multicolumn{1}{c} {D3} &
\multicolumn{1}{c} {D4} &
\multicolumn{1}{c} {D5} &
\multicolumn{1}{c} {D6} &
\multicolumn{1}{c} {D7} &
\multicolumn{1}{c} {D8} \\
A &   70 &    80.81 &   54.5 & 100 & 51 & 88&  99 & 90\\
B &   66 &     99 &   73 & 88 & 66 &  59&  88 & 60\\
\toprule
\end{tabular}
}{}
\end{table}
\end{document}

答案1

\cellcolor可用于改变单元格的背景颜色:

在此处输入图片描述

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{pgf}
\usepackage{collcell}
\usepackage{booktabs}

% This selects the amount of color to use
\newcommand*{\MinNumber}{0}%
\newcommand*{\MaxNumber}{100}%

\newcommand{\ApplyGradient}[1]{%
  \pgfmathsetmacro{\PercentColor}{100.0*(#1-\MinNumber)/(\MaxNumber-\MinNumber)}%
  %\textcolor{black!\PercentColor}{#1}
  \edef\x{\noexpand\cellcolor{black!\PercentColor}}\x\textcolor{white}{#1}%
}
\newcolumntype{R}{>{\collectcell\ApplyGradient}{r}<{\endcollectcell}}

\begin{document}

\begin{tabular}{ c R R R R R R R R}
  \toprule
  \multicolumn{1}{c} {Tools} &
  \multicolumn{1}{c} {D1} &
  \multicolumn{1}{c} {D2} &
  \multicolumn{1}{c} {D3} &
  \multicolumn{1}{c} {D4} &
  \multicolumn{1}{c} {D5} &
  \multicolumn{1}{c} {D6} &
  \multicolumn{1}{c} {D7} &
  \multicolumn{1}{c} {D8} \\
  A &   70 &    80.81 &   54.5 & 100 & 51 & 88&  99 & 90\\
  B &   66 &     99 &   73 & 88 & 66 &  59&  88 & 60\\
  \toprule
\end{tabular}

\end{document}

为了让 能够\PercentColor“看到” \cellcolor,我们首先展开表达式,然后\cellcolor使用\edef\x{..}\x技巧调用。这对单元格来说是本地的。

在末尾的使用\toprule看起来很奇怪,但是它允许底行的单元格颜色延伸到水平规则。

相关内容