[Tex/LaTex] Use CSV data in table caption

captionscsvcsvsimpleimport

I want to use some data, imported with csvsimple, in a table caption.

\begin{filecontents*}{data.csv}
column1,column2,column3
name1,val1a,val1b
name2,val2a,val2b
\end{filecontents*}

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{csvsimple}

\newcommand{\csvget}[3]{\csvreader[no head, filter equal={\thecsvinputline}{#2}]{#1}{}{#3}}

\begin{document}
\listoftables

\begin{table}
   \centering
   My Tabular
   \caption{A caption \csvget{data.csv}{2}{\csvcolii}}
\end{table}

\end{document}

Using the code from above I get an error like Argument of \@caption has an extra...
Any suggestions?

Thanks in advance
CX

Best Answer

This is a problem with fragile commands. See What is the difference between Fragile and Robust commands?

With e-tex compatible compiler you may use \newrobustcmd from etoolbox:

\begin{filecontents*}{data.csv}
column1,column2,column3
name1,val1a,val1b
name2,val2a,val2b
\end{filecontents*}

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{csvsimple}
\usepackage{etoolbox}

\newrobustcmd{\csvget}[3]{\csvreader[no head, filter equal={\thecsvinputline}{#2}]{#1}{}{#3}}

\begin{document}
\listoftables

\begin{table}
   \centering
   \csvautotabular{data.csv}
   \caption{A caption \csvget{data.csv}{2}{\protect\csvcolii}}
\end{table}

\end{document}

Without it you may use \DeclareRobustCommand

\begin{filecontents*}{data.csv}
column1,column2,column3
name1,val1a,val1b
name2,val2a,val2b
\end{filecontents*}

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{csvsimple}

\DeclareRobustCommand{\csvget}[3]{\csvreader[no head, filter equal={\thecsvinputline}{#2}]{#1}{}{#3}}

\begin{document}
\listoftables

\begin{table}
   \centering
   \csvautotabular{data.csv}
   \caption{A caption \csvget{data.csv}{2}{\protect\csvcolii}}
\end{table}

\end{document}

the result is:

result