TransWikia.com

Automatic Numbering and Color in Table

TeX - LaTeX Asked by Eric Williams on February 2, 2021

I’m trying to simultaneously get a column which automatically lists the row number but is colored similarly to xcolor‘s rowcolors command. That is, I’m trying to get an output similar to:

usepackage[table]{xcolor}

begin{document}

rowcolors{2}{green!60!yellow!40}{green!40!yellow!20}

begin{tabular}{|p{2em}|p{1in}|p{1in}|}
hline
cellcolor{violet!20} ID & cellcolor{violet!20} Description  & cellcolor{violet!20} Location
1 & Lorem & ipsum
2 & Dolor & dolor
3 & Foo & bar
hline
end{tabular}

end{document}

while using an implementation similar to:

usepackage[table]{xcolor}

begin{document}

newcounter{rownum}
setcounter{rownum}{1}

newcommand{rownumber}{arabic{rownum} stepcounter{rownum}}

rowcolors{2}{green!60!yellow!40}{green!40!yellow!20}

begin{tabular}{|@{makebox[2em][r]{rownumber~}}|p{1in}|p{1in}|}
hline
multicolumn{1}{|@{makebox[2em][r]{ID~}} | l |}{cellcolor{violet!20}Description} & cellcolor{violet!20} Location
Lorem & ipsum
Dolor & dolor
Foo & bar
hline
end{tabular}

end{document}

The first "target" implementation is generates:Table with correct coloring, but no automatic numbering

The implementation that uses automatic numbering generates:enter image description here

How can I get the coloring from the first without needing to put the numbers in manually (or prepending each line with a command)?

One Answer

Here is a possible approach:

enter image description here

>{command} allows to include formatting commands, which be executed with each cell. Furthermore, you need to define additionally cell color with cellcolor{...} inside multicolumn

documentclass{standalone}
usepackage{array}
usepackage[table]{xcolor}
newcounter{rownum}
setcounter{rownum}{0}
rowcolors{2}{green!60!yellow!40}{green!40!yellow!20}
begin{document}
    begin{tabular}{|>{stepcounter{rownum}therownum}p{1em}|p{0.75in}|p{0.75in}|}
        hline
        multicolumn{1}{|p{1em}|}{cellcolor{violet!20}{ID}} & cellcolor{violet!20}Description & cellcolor{violet!20} Location
        &Lorem & ipsum
        &Dolor & dolor
        &Foo & bar
        hline
    end{tabular}
end{document}

Answered by Ñako on February 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP