使用 csvsimple,如何在标题下放置一行?

使用 csvsimple,如何在标题下放置一行?

我可以制作如下的简单表格:

\documentclass{article}
\usepackage{csvsimple}

\begin{filecontents*}{words.csv}
num, word
1, apple
2, dog
3, pizza
\end{filecontents*}

\begin{document}

\begin{tabular}{cl}
\bfseries Num & \bfseries Text 
\csvreader[head to column names]{words.csv}{}{\\\num & \word}
\\\hline
\end
{tabular}

\end{document}

但是当我尝试在标题下方添加一行时,如下所示:

\documentclass{article}
\usepackage{csvsimple}

\begin{filecontents*}{words.csv}
num, word
1, apple
2, dog
3, pizza
\end{filecontents*}

\begin{document}

\begin{tabular}{cl}
\bfseries Num & \bfseries Text 
\hline
\csvreader[head to column names]{words.csv}{}{\\\num & \word}
\\\hline
\end
{tabular}

\end{document}

我收到此错误:

./csv-simple-error.tex:16: Misplaced \noalign.
\hline ->\noalign 
              {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
 l.16 \hline

这个错误是什么意思?如何在标题下添加水平线?

答案1

\hline只能出现在格式声明之后或换行命令之后;因为示例代码中的\\第一个不是这种情况,并且会触发错误。以下是一个可能的解决方案:\hline

\documentclass{article}
\usepackage{csvsimple}

\begin{filecontents*}{words.csv}
num, word
1, apple
2, dog
3, pizza
\end{filecontents*}

\begin{document}

\begin{tabular}{cl}
\bfseries Num & \bfseries Text  \\
\hline
\csvreader[head to column names]{words.csv}{}{\num & \word\\}
\\[-\normalbaselineskip]\hline
\end
{tabular}

\end{document}

在此处输入图片描述

答案2

您可以使用late after line

\begin{filecontents*}{\jobname.csv}
num, word
1, apple
2, dog
3, pizza
\end{filecontents*}

\documentclass{article}
\usepackage{csvsimple}

\begin{document}

\begin{tabular}{cl}
\bfseries Num & \bfseries Text \\ \hline
\csvreader[
  head to column names,
  late after line=\\,
]{\jobname.csv}{}{\num & \word}
\hline
\end{tabular}

\end{document}

在此处输入图片描述

另一种方法是使用选项tabular\csvreader这意味着\\在行末尾:

\begin{filecontents*}{\jobname.csv}
num, word
1, apple
2, dog
3, pizza
\end{filecontents*}

\documentclass{article}
\usepackage{csvsimple}

\begin{document}

\csvreader[
  tabular=cl,
  head to column names,
  table head=\bfseries Num & \bfseries Text \\ \hline,
  table foot=\hline,
]{\jobname.csv}{}{\num & \word}

\end{document}

相关内容