LaTeX – Create a table from a CSV file with borders

bordercsvtables

As many of you, I wanted to automate as many things as possible when creating my files.
I have to create tables often, so I figured that loading from a CSV file would be the most comfortable for me. (If I could create plots with the same library that would also be great, but lets not get ahead of myself now) So I found the datatool package:

\begin{figure}
\centering
\begin{tabular}{ |cccc| }
    \hline
    A & B & C & D \\
    \hline \hline
    \DTLforeach{data}{\A=A,\B=B,\C=C,\D=D}
    {\A & \B & \C & \D \\}
\end{tabular}
\end{figure}

This works and creates the tables almost exactly as I want to, but the problem starts with borders: generated table

How can I add the bottom one? It wouldn't accept \hline and I don't want to have a line at every line, just at the end of it.

My .csv file for example:

A,B,C,D
10,     60,     43,     43
20,     120,    42,     42
30,     180,    42,     42
40,     240,    42,     42
50,     300,    41,     41
60,     360,    40,     40
70,     420,    38,     38
80,     480,    35,     35
90,     540,    32,     32
100,    600,    29,     29
110,    660,    25,     25
120,    720,    21,     21
130,    780,    16,     16
140,    840,    12,     12
150,    900,    9,      9

If you think some other package is better, please let me know. (maybe csvsimple?)

Thanks!

Best Answer

Just use \DTLiffirstrow:

\documentclass{article}
\usepackage{datatool}
\begin{filecontents}{data}
A,B,C,D
10,     60,     43,     43
20,     120,    42,     42
30,     180,    42,     42
40,     240,    42,     42
50,     300,    41,     41
60,     360,    40,     40
70,     420,    38,     38
80,     480,    35,     35
90,     540,    32,     32
100,    600,    29,     29
110,    660,    25,     25
120,    720,    21,     21
130,    780,    16,     16
140,    840,    12,     12
150,    900,    9,      9
\end{filecontents}
\begin{document}
\DTLloaddb{data}{data}%
\begin{figure}
\centering
\begin{tabular}{ |cccc| }
    \hline
    A & B & C & D 
    \DTLforeach{data}{\A=A,\B=B,\C=C,\D=D}
    {\DTLiffirstrow{\\
    \hline \hline}{\\}%
    \A & \B & \C & \D}
    \\\hline
\end{tabular}
\end{figure}
\end{document}

enter image description here