[Tex/LaTex] Automatic table row numbers

numberingtables

Is there any way to get automatic row numbers in table?

For example, if I define table contents as

\begin{tabular} % black magic column definition
   \rownumber & foo\\
   \rownumber & bar\\
   \rownumber & baz\\
\end{tabular}

and get something like

1 | foo
2 | bar
3 | baz

Best Answer

\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\newcommand\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}}
\begin{document}

\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
  Something \\
  Other stuff \\
  MAGIC!
\end{tabular}

\end{document}

output

enter image description here
If you want to start with the second row use

\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\def\rownumber{}
\begin{document}

\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
  Something 
  \gdef\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}} \\
  Other stuff \\
  MAGIC!
\end{tabular}

\end{document}

output
enter image description here

If one wants a heading for the columns use:

\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\newcommand\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}}
\begin{document}

\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
\multicolumn{1}{@{\makebox[3em][r]{ID~}} | r}{\emph{whatever}}\\    
        Something \\
        Other stuff \\
        MAGIC!
\end{tabular}

\end{document}

enter image description here