我想动态生成表格列,但我不知道如何告诉 LaTeX 接受或评估&
作为列分隔符。
正如您在所附代码中看到的,问题在于\@for \el:=#1\do{\textbf{\el} &}
,其中&
应该分隔列和列标题。如果我删除字符&
,我会在第一列中得到整个字符串。这对我来说很有意义,因为表格单元格是用 分隔的&
。我怎样才能让它与单独的列一起工作?
\documentclass{article}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{forloop}
\usepackage{xstring}
\makeatletter
% http://tex.stackexchange.com/a/107298
\newcommand*{\commalength}[1]{%
\StrCount{#1,}{,}%
}
% http://tex.stackexchange.com/a/87420
\newcommand{\columnheader}[1]{%
% if i remove the "&" it works as a whole string but not splitted in columns
% HERE IS THE BUG WITH THE "&"
\@for \el:=#1\do{\textbf{\el} &}%
}
\makeatother
\newcommand{\generatecolumns}[1]{
% getting the column count automatically would be really nice like \commalength{#1}
\multicolumn{5}{l}{\emph{Continuation of \tablename\ \thetable{}}} \\
\toprule
% the column titles should be generated here ...
\columnheader{#1} \\ \midrule
\endhead
\hline
\multicolumn{5}{l}{\emph{Continued on next page}} \\
\bottomrule
\endfoot
}
\begin{document}
\begin{longtable}{lllll}
% this are the column titles
\generatecolumns{Column1,Column2,Column3,Column4,Column5}
\newcounter{i}
\forloop{i}{1}{\value{i} < 100}{
\arabic{i} & a & b & c & d \tabularnewline
}
\end{longtable}
\end{document}
答案1
对齐的时间安排可能很棘手,这里的主要问题是它&
不仅仅是一个对齐标记,它是一个 TeX 组,{}
因此如果您评估表内的循环,则在循环的一次迭代中开始的组将在下一次迭代中结束,并且大多数循环宏无法应对。
在标记寄存器或宏中构建整行通常更容易。
由于您正在使用 LT,它已经计算了列数,因此您不需要这样做。
\documentclass{article}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{forloop}
\usepackage{xstring}
\makeatletter
% http://tex.stackexchange.com/a/87420
\newcommand{\columnheader}[1]{%
\gdef\thisheader##1{}%
% if i remove the "&" it works as a whole string but not splitted in columns
% HERE IS THE BUG WITH THE "&"
\@for \el:=#1\do{\protected@xdef\thisheader{\thisheader&\el}%
}}
\newcommand{\generatecolumns}[1]{
% getting the column count automatically would be really nice like \commalength{#1}
\multicolumn{\LT@cols}{l}{\emph{Continuation of \tablename\ \thetable{}}} \\
\toprule
\noalign{\columnheader{#1}}\thisheader \\ \midrule
\endhead
\hline
\multicolumn{5}{l}{\emph{Continued on next page}} \\
\bottomrule
\endfoot
}
\makeatother
\begin{document}
\begin{longtable}{lllll}
% this are the column titles
\generatecolumns{Column1,Column2,Column3,Column4,Column5}
\newcounter{i}
\forloop{i}{1}{\value{i} < 100}{
\arabic{i} & a & b & c & d \tabularnewline
}
\end{longtable}
\end{document}