4

I've a CSV file what I want process with csvsimple. My desire is to color some rows based on a conditional (one specified column has bigger value). Here is an MWE:

\documentclass[12pt]{article}
\usepackage{filecontents}
\usepackage{csvsimple}
\usepackage[table]{xcolor}
\begin{document}
\begin{filecontents*}{mwe.csv}
a,b,c,d
1,1,2,2
1,3,2,1
\end{filecontents*}
\begin{tabular}{*{4}{c}}
  \csvreader[
    head to column names,
    before line={\ifnum\d>1\rowcolor{gray}\fi},
    late after line={\\}
  ]{mwe.csv}{}{
    \a&\b&\c&\d
  }
\end{tabular}
\end{document}

In this case I gave an error message:

! Misplaced \noalign.  
<recently read> \noalign                             
l.18   }

How can I solve it?

uzsolt
  • 1,431

2 Answers2

6

Your error stems from \rowcolornot being at the very beginning of the row. You can fix that by adding an additional \\ at the beginning of a row. It would also be better to use a filter (section 3.4 of the manual) to process conditionals:

\documentclass[12pt]{article}
\usepackage{csvsimple}
\usepackage[table]{xcolor}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.csv}
a,b,c,d
1,1,2,2
1,3,2,1
3,4,5,0
6,7,8,1
8,6,4,2
9,1,2,4
0,0,1,1
\end{filecontents*}


\begin{document}
\begin{tabular}{*{4}{c}}
\csvreader[head to column names,
           full filter=\ifnumgreater{\d}{1}
                       {\\\rowcolor{gray} \csvfilteraccept}
                       {\\                \csvfilteraccept}
           ]{\jobname.csv}{}{\csvlinetotablerow}%
\end{tabular}
\end{document}

enter image description here

DG'
  • 21,727
1

Try this solution. It adds a line break after each row.

 
\documentclass[12pt]{article}
\usepackage{filecontents}
\usepackage{csvsimple}
\usepackage[table]{xcolor}
\begin{document}
\begin{filecontents*}{mwe.csv}
a,b,c,d
1,1,2,2
5,3,9,1
7,8,2,9
5,3,9,1
5,3,9,1
7,8,2,9
\end{filecontents*}

  \csvreader[tabular=cccc,
    head to column names,
    before line={\ifnum\d>1\\\rowcolor{gray}\else\\\fi}
  ]{mwe.csv}{}{
    \a&\b&\c&\d
  }


\end{document}

enter image description here

If you don't \else\\ then you will have this result:

enter image description here

Compiii
  • 11
  • There are empty lines. Compare it without the before line={\ifnum\d>1\\\rowcolor{gray}\else\\\fi} option! – uzsolt Jan 02 '19 at 09:45
  • I want equal height :) – uzsolt Jan 02 '19 at 09:49
  • @Compiii Your solution works great, if you omit the option tabular=cccc, (it adds an additional line break at the end) and put the whole \csvreader-statement inside of the tabular-environment. – DG' Jan 02 '19 at 11:04