2

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.

  • 4
    short answer no, latex does not have this information by default, there is some code in longtable that you could extract (it doesn't really depend on the rest of the package) it's slightly complicated because the preamble part {|c|c|c|} here might be bigger than the actual table, eg ams matrices have a 10 column preamble even if they have fewer actual columns, so if you have |c|c|c| but only two items in each row, tex discards the final c| but do you want the answer to be 3 or 2. – David Carlisle Jun 26 '18 at 7:06
  • Just out of curiosity: Is there something keeping you from counting the number of columns in the argument of \begin{tabular}{...}? – Mico Jun 26 '18 at 8:14
  • 1
    @Mico Do you mean counting the number of columns manually? If yes, the correct answer is laziness. However, if you refer to an automatic solution--well, I have no idea at the moment how to parse such an complex argument involving the S column type from the siunitx package and much more ... – Matthias Jun 26 '18 at 8:28
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.