
我想在表格環境中交替行顏色。我發現 colortbl 很有用。為了簡化編寫,我建立了以下巨集來交替行顏色(請參見下面的 MWE)。但是,我不明白為什麼\crc
宏不能與\multicolumn
, while\rca
或\rcb
像魅力一樣共存。
而且,更重要的是,如何簡化編寫,例如我總是使用相同的巨集名稱來替換顏色,即使我正在使用\multicolumn
?
\documentclass {article}
\usepackage {colortbl}
\begin {document}
% define row colors A and B
\def\rca{\rowcolor [rgb] {0.90, 0.95, 1.0}}
\def\rcb{\rowcolor [rgb] {0.80, 0.90, 1.0}}
% This one works like a charm
\begin {tabular} {|l|l|} \hline
\rca \multicolumn {1} {|c|} {one} & 1 \\ \hline
\rcb two & 2 \\ \hline
\rca three & 3 \\ \hline
\end {tabular}
% use current row color and set color for next row
\def\cseta{\gdef\crc{\rca\csetb}}
\def\csetb{\gdef\crc{\rcb\cseta}}
\cseta % (re)set \crc to the row color A
% This one does not want to compile!
% ! Misplaced \omit.
% \multispan ->\omit
% \@multispan
% l.23 \crc \multicolumn {1} {|c} {one}
% & 1 \\ \hline
\begin {tabular} {|l|l|} \hline
\crc \multicolumn {1} {|c} {one} & 1 \\ \hline
\crc two & 2 \\ \hline
\crc three & 3 \\ \hline
\end {tabular}
\end {document}
答案1
\multicolumn (和 \rowcolor)想要成為單元格中的第一件事。之前的一些內容是可以的,但它必須是可擴展的,並且只能擴展到空格。
您在 \multicolumn 之前使用 \gdef ,這是不可擴展的,因此不起作用。
\documentclass{article}
\usepackage{colortbl}
\newcommand\CAred{\rowcolor{red}}
\DeclareRobustCommand\CBred{\rowcolor{red}}
\newcommand\CCred[1][]{\rowcolor{red}}
\newcommand\CD{ }
\newcommand\CE{\,}
\begin{document}
\begin{tabular}{l}
\rowcolor{red}\multicolumn{1}{r}{blub}\\ %work
\CAred\multicolumn{1}{r}{blub} \\ %work
%\CBred\multicolumn{1}{r}{blub} \\ %fails (robust command)
%\CCred\multicolumn{1}{r}{blub} \\ %fails (optional argument -> not expandable
\CD\multicolumn{1}{r}{blub} \\ %works
%\CE\multicolumn{1}{r}{blub} \\ %fails (content)
%\relax\multicolumn{1}{r}{blub} \\ %fails
%\def\xy{blub}\multicolumn{1}{r}{blub}\\ %fails (definition)
%\parindent=10pt \multicolumn{1}{r}{blub}\\ %fails (assignment)
%blub\multicolumn{1}{r}{blub} \\ %fails (content)
\end{tabular}
\end{document}
答案2
感謝 Ulrike Fischer 關於 的建議\noalign
,這是一個可行的解決方案:
\documentclass {article}
\usepackage {colortbl}
\begin {document}
% define row colors A and B
\def\rca{\rowcolor [rgb] {0.90, 0.95, 1.0}}
\def\rcb{\rowcolor [rgb] {0.80, 0.90, 1.0}}
\begin {tabular} {|l|l|} \hline
\rca \multicolumn {1} {|c|} {one} & 1 \\ \hline
\rcb two & 2 \\ \hline
\rca three & 3 \\ \hline
\end {tabular}
% use current row color and set color for next row
\def\cseta{\noalign {\gdef\crc{\rca\csetb}}}
\def\csetb{\noalign {\gdef\crc{\rcb\cseta}}}
\gdef\crc{\rca\csetb} % (re)set \crc to the row color A
\begin {tabular} {|l|l|} \hline
\crc \multicolumn {1} {|c} {one} & 1 \\ \hline
\crc two & 2 \\ \hline
\crc three & 3 \\ \hline
\end {tabular}
\end {document}