根据内容编程表格单元格颜色

根据内容编程表格单元格颜色

我根据之前的问答

在此处输入图片描述

如您所见,标题存在问题。
如何禁用仅标题的突出显示?

代码如下:

\documentclass{article}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{xcolor}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother

\begin{document}
\begin{table}[htp]
\caption{XOR}
\begin{center}
\begin{tabular}{CCCCCCCCCCCCCCCCCC}

\toprule
$Bit$       &   1   &   2   &   3   &   4   &   5   &   6   &   7   &   8   \\
\midrule 
$A$         &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
$B$         &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
$\bigoplus$ &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
\bottomrule

\end{tabular}
\end{center}
\label{XOR}
\end{table}

\end{document}

答案1

像这样?

在此处输入图片描述

修复(完成)您的 MWE 后...我建议对定义的列标题使用不同类型的列类型\multicolumn{1}{c}{...}

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

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother
\newcommand\mc[1]{\multicolumn{1}{c}{#1}} % <--- new

\begin{document}
    \begin{table}[htp]
\caption{XOR}
\centering
\begin{tabular}{l| *{8}{C}}
    \toprule
$Bit$       &\mc{1} &\mc{2} &\mc{3} &\mc{4} &\mc{5} &\mc{6} &\mc{7} &\mc{8} \\ % <--- changed
    \midrule
$A$         &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
$B$         &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
$\bigoplus$ &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
    \bottomrule
\end{tabular}
\label{XOR}
    \end{table}
\end{document}

注意:表格中的垂直线和规则的使用booktabs效果不佳。您应该考虑其他组合(例如\hlineB{...}来自boldline包):

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{boldline}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother
\newcommand\mc[1]{\multicolumn{1}{c}{#1}} % <--- new

\begin{document}
    \begin{table}[htp]
\caption{XOR}
\centering
\begin{tabular}{>{\rule[-1ex]{0pt}{4ex}$}l<{$} | *{8}{C}}
    \hlineB{2}
\mathrm{Bit} &\mc{1} &\mc{2} &\mc{3} &\mc{4} &\mc{5} &\mc{6} &\mc{7} &\mc{8} \\ % <--- changed
    \hlineB{1.5}
A            &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
B            &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
\bigoplus    &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
    \hlineB{2}
\end{tabular}
\label{XOR}
    \end{table}
\end{document}

在此处输入图片描述

相关内容