8

I am certain this is patently obvious, but the solution is eluding me...

Given a dataset stored in CSV:

ID,    col1,  col2, col3
KEY-1, foo    bar,  baz
KEY-2, alice, bob,  chuck

I would like to define a macro \getCol3{KEY-2} that returns chuck. I am getting tripped up by what appears to be internal key structures (and the fact that I just started using datatool).

\DTLgetvalue{\thevalue}{data}{\therow}{\thecol}

is what I assumed was in the right direction, but I cannot construct valid values for \therow and \thevalue.

Werner
  • 603,163

1 Answers1

5

You need to use \DTLgetvalueforkey

\begin{filecontents*}{demo.csv}
ID,    col1,  col2, col3
KEY-1, foo,   bar,  baz
KEY-2, alice, bob,  chuck
\end{filecontents*}
\documentclass{article}
\usepackage{datatool}
\DTLloaddb{data}{demo.csv}
\newcommand*{\thevalue}{}
\newcommand*{\getCol}[2]{%
  \DTLgetvalueforkey{\thevalue}{col#1}{data}{ID}{#2}%
}
\getCol{3}{KEY-2}
\show\thevalue

Here, we are using ID as the reference key to find the appropriate row, which is found using the argument #2.

Werner
  • 603,163
Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036