1

I have a csv file called "data.csv" containing the following data:
1,2,3
4,5,6

I am writing the following table in Latex by using \csvreader:

\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
    no head,
    late after line=\\,
    late after last line=,
    ]{data.csv}{}{\csvcoli & \csvcolii & \csvcoliii} \\
\hline
\end{tabular}
\end{table}

Which correctly yields what I want, i.e.:
enter image description here

However, instead of manually typing \csvcoli & \csvcolii & \csvcoliii inside \csvreader, I'd like to achieve that through a for loop. So I've written the following code:

\newcommand{\mycommand}[1]{
    \foreach \i in {1,...,#1}{
        \ifnum\i > 1 
            \& 
        \fi
        \csname csvcol\romannumeral\i\endcsname
    }
}


\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
    no head,
    late after line=\\,
    late after last line=,
    ]{data.csv}{}{\mycommand{3}} \\
\hline
\end{tabular}
\end{table}

However, this yields the following:
enter image description here

Can you please help me? Thanks a lot in advance.

2 Answers 2

3

This can be conveniently done with the readarray package.

\begin{filecontents*}[overwrite]{data.csv}
1,2,3
4,5,6
\end{filecontents*}
\documentclass{article}
\usepackage{readarray}
\readarraysepchar{,}
\readdef{data.csv}\mydata
\readarray*\mydata\myarray[-,\ncols]
\renewcommand\typesetrowsepchar{\\}
\renewcommand\typesetcolsepchar{&}
\begin{document}
\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\typesetarray\myarray\\
\hline
\end{tabular}
\end{table}
\end{document}

enter image description here

1
  • 1
    I didn't know about readarray package, it seems very convenient!
    – CarLaTeX
    Commented Mar 22 at 7:14
3

csvsimple-l3 provides \csvlinetotablerow which does exactly what you want. csvsimple-l3 can be loaded with either \usepackage[l3]{csvsimple} or usepackage{csvsimple-l3}

\begin{filecontents*}[noheader,overwrite]{data.csv}
1,2,3
4,5,6
\end{filecontents*}

\documentclass{article}
\usepackage{csvsimple-l3}

\begin{document}
Original, using \verb|\csvcoli & \csvcolii & \csvcoliii|\par
\begin{tabular}{|c|c|c|}
  \hline
  Sue & Karl & Tim \\
  \hline
  \csvreader[
      no head,
      late after line=\\,
      late after last line=,
      ]{data.csv}{}{\csvcoli & \csvcolii & \csvcoliii} \\
  \hline
\end{tabular}
\medskip

Using \verb|\csvlinetotablerow|\par
\begin{tabular}{|c|c|c|}
  \hline
  Sue & Karl & Tim \\
  \hline
  \csvreader[
      no head,
      late after line=\\,
      late after last line=,
      ]{data.csv}{}{\csvlinetotablerow} \\
  \hline
\end{tabular}
\medskip

Using \verb|\csvautotabular|\par
\csvautotabular*[
  table head={\hline Sue & Karl & Tim \\ \hline}
]{data.csv}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .