[Tex/LaTex] Importing CSV as Long Table Not Working

csvcsvsimpleimportlongtabletables

I tried implementing the solution found here with multiple columns, but it is not working for me. It is just replicating the third column three times. What am I doing wrong? I know I wouldn't need a long table for this data in particular, but this is just a shortened version, and the problem I have still occurs.

\begin{filecontents*}{sample_data.csv}
    Col1,Col2,Col3,ColPct
    111,65,64,5\%
    112,30,5,6\%
    113,92,1,8.4\%
    114,47,19,20\%
    115,38,15,1\%
\end{filecontents*}

\documentclass{article}

\usepackage{csvsimple,longtable,booktabs}
\begin{document}

    \csvreader[
    longtable=lrrrr,
    table head=
    \toprule\bfseries Col1 &\bfseries Col2 & \bfseries Col3 & \bfseries ColPct\\ 
    \midrule\endhead\bottomrule\endfoot,
    late after line=\\,
    before reading={\catcode`\#=12},after reading={\catcode`\#=6}
    ]{Data/sample_data.csv}{1=\Item,2=\Item, 3=\Item, 4=\Percentage}
    {\Item & \Item & \Item & \Percentage}
\end{document}

results

Best Answer

Using a unique macro for each column that you want to import, will lead to the desired output:

\begin{filecontents*}{sample_data.csv}
    Col1,Col2,Col3,ColPct
    111,65,64,5\%
    112,30,5,6\%
    113,92,1,8.4\%
    114,47,19,20\%
    115,38,15,1\%
\end{filecontents*}

\documentclass{article}

\usepackage{csvsimple,longtable,booktabs}
\begin{document}

    \csvreader[
    longtable=lrrrr,
    table head=
    \toprule\bfseries Col1 &\bfseries Col2 & \bfseries Col3 & \bfseries ColPct\\ 
    \midrule\endhead\bottomrule\endfoot,
    late after line=\\,
    before reading={\catcode`\#=12},after reading={\catcode`\#=6}
    ]{sample_data.csv}{1=\ColOne, 2=\ColTwo, 3=\ColThree, 4=\Percentage}
    {\ColOne & \ColTwo & \ColThree & \Percentage}
\end{document}

enter image description here


From the csvsimple manual:

The csvsimple package is applied to the processing of CSV files. This processing is controlled by key value assignments [...]

See: Introduction, page 1

\csvreader[<options>]{<file name>}{<assignments>}{<command list>} [...] The <assignments> are given by key value pairs <name>=<macro>. Here, <name>is an entry from the header line or the arabic number of the addressed column. <macro>is some TEX macro which gets the content of the addressed column. [...]

See: Macros for the Processing of CSV Files, page 8

If you use the identical macro for two different columns, you assign the contents of the first column to this macro. With the assignment of the contents of the second column, you then overwrite the first assignment. This will then lead to the observed output where all columns with the same macro contain the contents of the last column.