Search code examples
csvlatexpdflatex

Problem with \bottomrule when using booktabs and \csvreader together, missplaced \noalign Latex


I am trying to implement this table into a bigger document but I am unable to do so. If I don't use \bottomrule then it works fine but when I try to add that line it gives the error "misplaced \noalign".

.tex File:

\documentclass{article}
\usepackage{csvsimple}
\usepackage{booktabs}
\usepackage{multirow}

\begin{document}

\begin{table}
\centering
\begin{tabular}{cccccc}
\toprule
\multirow{2}{*}{Substituent (R)} & \multicolumn{2}{c}{P} & \multicolumn{2}{c}{As} \\
\cmidrule(lr){2-3} \cmidrule(lr){4-5}
& C1 & C2 & C3 & C4 \\
\midrule
\csvreader{var.csv}{}{
  \csvcoli & \csvcolii & \csvcolii & \csvcoliv & \csvcolv\\}
\bottomrule
\end{tabular}
\caption{Example table with bottom rule using csvsimple}
\end{table}

\end{document}

var.csv:

A,B,C,D,E
1,2,3,0,2
5,6,7,6,7

I tried to insert \before bottomrule but then it leaves a large space before the line. Also if I don't use csvreader and I simply type out the table then it's fine, the line appears as is supposed to. But this is not really efficient because I have to create multiple tables with lots of rows so it would be really time consuming to type them out. Thank you in advance.


Solution

  • You can use the late after line=\\ option to start new tabular lines when you read the csv file:

    \documentclass{article}
    \usepackage{csvsimple}
    \usepackage{booktabs}
    \usepackage{multirow}
    \usepackage{array}
    
    \begin{filecontents*}[overwrite]{var.csv}
    A,B,C,D,E
    1,2,3,0,2
    5,6,7,6,7
    \end{filecontents*}
    
    \begin{document}
    
    \begin{table}
    \centering
    \begin{tabular}{cccccc}
    \toprule
    \multirow{2}{*}{Substituent (R)} & \multicolumn{2}{c}{P} & \multicolumn{2}{c}{As} \\
    \cmidrule(lr){2-3} \cmidrule(lr){4-5}
    & C1 & C2 & C3 & C4 \\
    \midrule
    \csvreader[late after line=\\]{var.csv}{}{
      \csvcoli & \csvcolii & \csvcolii & \csvcoliv & \csvcolv}
    \bottomrule
    \end{tabular}
    \caption{Example table with bottom rule using csvsimple}
    \end{table}
    
    \end{document}