5

I am trying to generate a numbered table. I used the answer here, which put @{\stepcounter{rowcount}} into the first line of the tabular.

However, this seems to break when I try to use the booktabs package, or even the plain tabular format. I suspect the problem is because \stepcounter is fragile, but I don't know how to solve the problem.

I'd also like to make the first row a header, without a number.

Here is the MWE

\documentclass{article}
\usepackage{booktabs}
\newcounter{rowcounter}
\setcounter{rowcounter}{0}
\begin{document}

\begin{tabular}{@{\stepcounter{rowcounter}\arabic{rowcounter}}ll} 
header row & text0\\ 
first row & text1\\
second row & text1\\
third row & text2

\end{tabular}
\end{document}
Tim
  • 1,539

2 Answers2

9

In preamble you need add array package:

\documentclass{article}
\usepackage{array,  % <-- added
            booktabs}
\newcounter{rowcounter}
\setcounter{rowcounter}{0}

\begin{document}

\begin{tabular}{@{\stepcounter{rowcounter}\arabic{rowcounter}\ }ll}
header row & text0\\
first row & text1\\
second row & text1\\
third row & text2
\end{tabular}
\end{document}

enter image description here

Zarko
  • 296,517
7

If you don't use array you need to \protect the commands

\documentclass{article}
\usepackage{booktabs}
\newcounter{rowcounter}
\setcounter{rowcounter}{0}
\begin{document}

\begin{tabular}{@{\protect\stepcounter{rowcounter}\protect\arabic{rowcounter} }ll} 
header row & text0\\ 
first row & text1\\
second row & text1\\
third row & text2

\end{tabular}
\end{document}

If you want to start at 0 then you could either initialise to -1 instead of 0 or in the @{} use the counter before you increment it rather than after.

David Carlisle
  • 757,742
  • Can you modify this to show how to make header row? I don't want the header row with 0, I want no number at all. Is having an if/then clause the best way? I tried having 2 tabular environments—one with header, the other with data— but can't get them aligned. And this may be an inefficient way to do it. – Tim Jan 22 '17 at 09:27
  • 1
    @Tim just use \multicoloumn{1}{@{}c}{header row} and that cell will not get the @{} from the preamble. – David Carlisle Jan 22 '17 at 09:52
  • yes it worked fine. – Tim Jan 22 '17 at 10:21