65

I want to have a longtable like this:

\begin{center}
\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}
\hline
1 & 2 & 3 & 4\\ 
\hline 
\hline
1 & 2 & 3 & 4\\
\hline
1 & 2 & 3 & 4\\
\hline
.
.
.
1 & 2 & 3 & 4\\
\hline

\label{variability_impl_mech}
\end{longtable}
\end{center}

but when I try to compile this, I get this error: !Misplaced \noalign

when I write the caption after the last \hline, it works fine. I want to have the caption on top of my table but this error appears.

AshKan
  • 951
  • 6
    To start with, remove the \begin{center} and \end{center} instructions -- a longtable is automatically centered. Second, add a double backslash after \caption{...}. – Mico Dec 22 '14 at 20:44

3 Answers3

62
\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}\\    %%%%<===
\hline

and you should put the \label after \caption, which makes more sense.

  • 13
    As an addition to the original answer using the label after caption should be as \caption{my caption} \label{my label}\ not as \caption{my caption}\ \label{my label} – Amarjit Dhillon Jul 07 '18 at 20:52
  • 1
    For me it doesn't compile without \endfirsthead and \endhead. See @Benjamin McKay's answer. – user2340939 Sep 17 '20 at 06:59
  • 2
    In my current version of Miktex (and when pushed up to overleaf), compilation would stall and hang without adding the "\" after the caption command. Hopefully that will help others running into this problem in the current version. – jgoeders Nov 18 '20 at 15:59
26

Another way: use head and first head:

\documentclass{article}
\usepackage{longtable}
\begin{document}

\begin{longtable}{|p{2cm}|p{3cm}|p{7cm}|p{3cm}|}
\caption{my caption}
\label{variability_impl_mech}
\endfirsthead
\endhead
\hline
1 & 2 & 3 & 4\\ 
%\hline 
\hline
1 & 2 & 3 & 4\\
\hline
1 & 2 & 3 & 4\\
\hline
.
.
.
1 & 2 & 3 & 4\\
\hline
\end{longtable}

\end{document}
David Carlisle
  • 757,742
0

I had a problem with it, because I generate my tables with the library pandas from python. In this way.

print(tabla_1.to_latex(index = False, longtable=True))

But the problem is that pandas generate my longtables in this way:

\begin{longtable}{lrrr}
\toprule
                  Nombre &  No datos &  P. rango &  total\_isnull \\
\midrule

So I tried to put \labeland \caption before \toprule, but it nevers compile. So my solution was change \toprule for \hline and then you'll have your compilation, example:

\begin{longtable}{lrrr}
\label{YourLabel}
\Caption{YourCaption}
\hline
                  Nombre &  No datos &  P. rango &  total\_isnull \\
\midrule
  • 2
    I create tables using pandas in the same way and I find things work properly when placing \caption{the caption}\label{the label}\\ after the \begin{longtable} line as mentioned by @Herbert – jeschwar Jan 07 '19 at 17:36
  • \toprule requires the booktabs package I believe. – Lukas Mar 25 '19 at 19:00