2

I have defined a style sheet which contains a table. Something along the following:

\begin{table}[h]
    \centering
    \begin{tabular}{ |c|c|c|c| }
        \hline
        Header 1 & Header 2 & Header 3 & Header 4 \\ \hline % Header row
        % Put table content here!
    \end{tabular}
\end{table}

What I want to do, is define some command in my style sheet that allows me to continually add content to this table in my preamble. I'm thinking of a command usage like the following:

\addtotable[1]{R1C1,R1C2,R1C3,R1C3}
\addtotable[2]{R2C1,R2C2,R2C3,R2C3}

Which would effectively result in the table being

\begin{table}[h]
    \centering
    \begin{tabular}{ |c|c|c|c| }
        \hline
        Header 1 & Header 2 & Header 3 & Header 4 \\ \hline % Header row
        R1C1     & R1C2     & R1C3     & R1C4     \\ \hline
        R2C1     & R2C2     & R2C3     & R2C4     \\ \hline
    \end{tabular}
\end{table}
zephyr
  • 493

1 Answers1

5

enter image description here

Place a macro at the point of the insertion then just incrementally add to that macro:

\documentclass{article}

\newcommand\foo{%
\begin{table}[htp]
    \centering
    \begin{tabular}{ |c|c|c|c| }
        \hline
        Header 1 & Header 2 & Header 3 & Header 4 \\ \hline % Header row
        \foorows
       \hline
    \end{tabular}
\end{table}}

\newcommand\foorows{}

\makeatletter
\newcommand\addtotable[1]{%
    \g@addto@macro\foorows{\@gobble}%
  \@for\tmp:=#1\do{%
 \expandafter\g@addto@macro\expandafter\foorows
                   \expandafter{\expandafter&\tmp}%
}%
    \g@addto@macro\foorows{\\}%
}
\makeatother

\addtotable{R1C1,R1C2,R1C3,R1C3}
\addtotable{R2C1,R2C2,R2C3,R2C3}
\begin{document}

\foo

\end{document}
David Carlisle
  • 757,742
  • This is great! Thanks. One addendum for those following, I did intend to put this in a style sheet which means I had to remove the \makeatletter and \makeatother commands for this to work. – zephyr Dec 01 '16 at 20:24