根據內容對表格單元格顏色進行編程

根據內容對表格單元格顏色進行編程

我根據之前的表建立了這個表問答:

在此輸入影像描述

正如您所看到的,標題有問題。
如何僅禁用標題的突出顯示?

這是代碼:

\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}

在此輸入影像描述

相關內容