# Datatool cannot use math macros in tabular headers from csv file

I am making a LaTeX table using a CSV file and the datatools package.

Here is a minimal working example:

\documentclass{minimal}
\usepackage{datatool}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
,$x$,$p_x$,
$x$,$0$,$i \hbar$
\end{filecontents*}

\begin{document}

\DTLdisplaydb{mytable}

\end{document}


This will compile cleanly. However, if I change the first row (which will become the header) to include a macro (e.g. ,$x$,$\hbar$,) I get a whole bunch of errors on the \DTLloaddb{mytable}{data.csv} line.

! Missing \endcsname inserted.
\mathchar
The control sequence marked <to be read again> should
not appear between \csname and \endcsname.
....(and so forth)...


Things I have tried that did not work:

1. Quoting ("\hbar")
2. Ensuremath (\ensuremath{\hbar})
3. Using tabs as delimiters instead of commas.
4. Unrolling the csv file into equivalent datatool commands.

These are the equivalent commands:

\DTLnewdb{mydata}
\DTLnewrow{mydata}%
\DTLnewdbentry{mydata}{}{$x$}%
\DTLnewdbentry{mydata}{$x$}{$0$}%
\DTLnewdbentry{mydata}{$p_x$}{$i \hbar$}%
\DTLdisplaydb{mydata}


They give the same errors as the csv file.

Manually specifying the headers, however, works fine:

\documentclass{minimal}
\usepackage{datatool}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
$x$,$0$,$i \hbar$
\end{filecontents*}

\begin{document}

\DTLloaddb[noheader,headers={,$x$,$\hbar$}]{mytable}{data.csv}

\DTLdisplaydb{mytable}

\end{document}


I would like to avoid manually specifying the headers, however, if possible.

• Welcome to TeX.SX! The culprit is \hbar, which is very fragile. Unfortunately even \protect does not help. :-( – egreg Jul 22 '13 at 21:29

The problem is that you're using something unexpandable as an identifying label. The same problem would arise if you tried doing something like \label{\hbar}. If the headers contain commands or special characters you need to explicitly set the keys to simple labels. For example:

\documentclass{article}
\usepackage{datatool}
\usepackage{filecontents}

\begin{filecontents*}{data.csv}
$x$,$0$,$i \hbar$
,$x$,$p_x$
\end{filecontents*}

\begin{document}


(You'll probably want something more descriptive than column1 etc.)