自动表格行号

自动表格行号

有没有什么办法可以让表格自动获得行号?

例如,如果我将表内容定义为

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

并得到类似

1 | foo
2 | bar
3 | baz

答案1

\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}

输出

在此处输入图片描述
如果你想从第二行开始使用

\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}

输出
在此处输入图片描述

如果想要列标题,请使用:

\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}

在此处输入图片描述

答案2

您可以让它使用计数器......

\documentclass{article}
\newcounter{magicrownumbers}
\newcommand\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}}
\begin{document}
\begin{tabular}{l|r}
  \rownumber & Something \\
  \rownumber & Other stuff \\
  \rownumber & MAGIC!
\end{tabular}
\end{document}

在此处输入图片描述

答案3

环境{NiceTabular}nicematrix自己的内置行计数器,称为iRow

\documentclass{article}
\usepackage{nicematrix}

\begin{document}

\begin{NiceTabular}{>{\arabic{iRow}}c|c}
&  Something \\
&  Other stuff \\
&  MAGIC!
\end{NiceTabular}

\end{document}

上述代码的输出

答案4

为了完整性,还提供快速的纯格式版本:

\newcount\rowcount
\def\myhalign#1{\halign{\global\advance\rowcount by 1 \the\rowcount\quad##&#1}\rowcount=0}
% Yes, yes, next up in *sniping*: "One problem: you can't use repeating preamble"...
\myhalign{#\hfil\cr
  blah\cr
  foo\cr}
\halign{#\hfil\cr
  bar\cr
  baz\cr}
\myhalign{&#\hfil\cr
  asdf&asdf&asdf\cr
  sdfg&asdf&dfgh\cr}
\myhalign{#\hfil&&\hfil#\cr
  doesn't&work\cr
  boo&hoo\cr}
\bye

相关内容