1

I know that the best way to altern row color is using \rowcolors{2}{}{} but on my .tex file \usepackage[table]{xcolor} doesn't work so I am trying to reach the same result with \if.

I would like to insert in \foreach this:

\if \i is odd then \rowcolor{grey!10} else nothing.

My code is the following.

\begin{table}
    \begin{tabular}{cccccc}
        \toprule
        {} & {\bf Carbon} & {\bf Hydrogen} & {\bf Nitrogen} & {\bf Oxygen\tnote{a}} & {\bf pH}\\
        \midrule
        \foreach \M[count=\i] in {a,b,c,d}{
            {\bf \M} & - & - & - & - & -\\
        }
        \bottomrule
    \end {tabular}
\end {table}

The result should be the following.

enter image description here

  • 2
    "doesn't work " what error do you get? Please always make your example scomplete documents so people can test answers. Your fragment uses several commands that are not defined by default in latex, so everyone has to guess which packages you are using. – David Carlisle Oct 12 '15 at 13:48
  • Please add a fully compilable MWE next time. – musicman Oct 12 '15 at 17:34
  • Please, note that \bf (like all similar two letter font commands) has been obsolete for 20 years. Use \bfseries or \textbf as described in any LaTeX guide. – egreg Oct 12 '15 at 20:53
2

I guess, the problem you walked in are for-loops inside tables. See here for example.

For my approach I used the forloop-package for iterating the numbers/letters, and etoolbox to robustify the linebreak-command. MWE:

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{booktabs}
\usepackage{forloop}
\usepackage{etoolbox}%for robustify


\def\tabledata{}
\def\lbr{\\}
\robustify\lbr%neverever expand

\newcounter{mynextrowc}
\newcommand\dummyrows[1]{%
    \forloop{mynextrowc}{1}{\value{mynextrowc} < #1}{%
        \edef\tabledata{\tabledata\alph{mynextrowc} & - & - & - & - & -\lbr}
    }%
}

\begin{document}
\dummyrows{15}

\rowcolors{2}{gray!25}{white}
\begin{table}
    \begin{tabular}{cccccc}
        \rowcolor{gray!50}
        \toprule
        {} & {\bf Carbon} & {\bf Hydrogen} & {\bf Nitrogen} & {\bf Oxygen {a}} & {\bf pH}\\
        \midrule
        \tabledata
        \bottomrule
    \end{tabular}
\end{table}
\end{document}

Output:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.