[Tex/LaTex] Determining the number of columns of a table

multicolumntables

In the MWE

\documentclass{article}

\begin{document}

\begin{tabular}{|c|c|c|} \hline
\multicolumn{3}{|c|}{Table header} \\ \hline
Column 1 & Column 2 & Column 3 \\ \hline
\end{tabular}

\end{document}

I use a multi-column that spans the whole table.

Is it possible to determine the number of columns automatically, e.g., by defining a command for creating a multi-column that spans all columns comprising the table?

This previous question seems to be specific to the longtable package.

Best Answer

I basically agree with the previous comments.

However, if you really want do this because the table will be generated programatically, and the number of column can change accordingly, yo can count the number of column by using list processing provided by etoolbox or by listofitems. Assuming that you keep te | between the columns, you can put in your preamble (etoĆ²lbox's \doccsvlist):

\global\newcounter{colno}
\setcounter{colno}{0}
\DeclareListParser{\countcol}{|}%
\renewcommand*{\do}[1]{\stepcounter{colno}}
\newenvironment{newtabular}[1]{
\countcol{#1}%
\begin{tabular}{#1}}%
{\end{tabular}}

and in the body :

\begin{newtabular}{|c|l|r|c|l|}
\hline
\multicolumn{\thecolno}{|c|}{Table header}\\
\hline
A & a & b & c & d\\
\thecolno & \the\numexpr\value{colno}-2\relax& 3 & 4 & 5 \\
\hline
\end{newtabular}

Note that the number of columns can also be used in the content of the table.