2

I want to read a csv into a table that I defined like follows:

\begin{table}[bp]
    \centering
    \caption{Reading csv.}
    \label{table:csv}
    \begin{tabular}{cccc}
    \toprule
    \multirow{2}{1.4cm}{\parbox{1\linewidth}{\vspace{1mm}A}} & \multirow{2}{0.9cm}{\parbox{1\linewidth}{\vspace{1mm} \centering B}} & \multicolumn{2}{c}{C} \\ \cmidrule{3-4}
    & & D & E  \\ \midrule
    A0      &   B0      &   D0      &   E0 \\
    A1      &   B1      &   D1      &   E1 \\
    A2      &   B2      &   D2      &   E2 \\
    \bottomrule
    \end{tabular}
\end{table}

The .csv looks like:

,B,C,
,,D,E
A0,B0,D0,E0
A1,B1,D1,E1
A2,B2,D2,E2

And the table should look like:

enter image description here

  1. How can I read the .csv?
  2. How can A be centered in the column?
  3. Should the .csv contain the headers of the table (A, B, C, D and E) or that should come from latex only?

Thanks for the help

EDIT: Would it be easier/better if the .csv looks like this?

A,B,D,E
A0,B0,D0,E0
A1,B1,D1,E1
A2,B2,D2,E2
aripod
  • 107
  • 1
    Do you have control over producing the CSV? If not, will it always be produced in this way? – Werner Mar 11 '21 at 18:22
  • I can make it however I want, that is why I asked question 3. It might be better to have:
    A,B,D,E
    A0,B0,D0,E0
    A1,B1,D1,E1
    A2,B2,D2,E2
    

    right?

    – aripod Mar 11 '21 at 18:23

1 Answers1

3

Here is an approach using datatool:

enter image description here

\documentclass{article}

\usepackage{datatool,booktabs}

\begin{filecontents}[overwrite]{table_data.csv} A,B,D,E A0,B0,D0,E0 A1,B1,D1,E1 A2,B2,D2,E2 \end{filecontents}

\begin{document}

\begin{table} \DTLloaddb{tabledata}{table_data.csv}% Load CSV data \centering \caption{Reading csv.} \begin{tabular}{ c c c c } \toprule & & \multicolumn{2}{c}{C} \ \cmidrule{3-4} A & B & D & E \ \midrule \DTLforeach{tabledata}{% \Acol=A, \Bcol=B, \Dcol=D, \Ecol=E% }{% \Acol & \Bcol & \Dcol & \Ecol \ } \[-\normalbaselineskip] \bottomrule \end{tabular} \end{table}

\end{document}

Werner
  • 603,163
  • That looks great. Thanks! One last thing is when the values of A are more than 2 characters, A is aligned to the left. How do you add the columns and their headings? – aripod Mar 11 '21 at 18:51
  • And what is the reason to use datatool and not csvsimple? – aripod Mar 11 '21 at 18:53
  • 1
    @aripod: The headers should be centred as that is how it is in the tabular column specification. I use datatool because I'm more familiar with it than with csvsimple. You can create "databases" with it, sort entries and process them. csvsimple is probably just a more elementary implementation that works just as well for your purposes. – Werner Mar 11 '21 at 19:34