4

I have a csv like the following:

CategoryName,Pageviews
Restaurants,37951
Shopping,22002
Things to do,20067
Nightlife,10612
Gifts,9194
Food Shopping,8655
Useful Stuff,8536
Parenting ,8353
Home,7654
Fitness,6623
Event & Party Planning,6387
Sports,4351
Health & Wellness,4201
Women's Beauty,3807
Pets,2923
Vehicles,2492
Male Grooming,2339
Hotels & Rentals ,2332
Charities,364

I'm using

\usepackage{csvsimple}

to read the csv and print it as a table with the following code.

\csvautotabular{cats.csv}

which doesn't work.

I've tried also

\begin{tabular}{l|c}%
\bfseries Category & \bfseries Metric
\csvreader[head to column names]{cats.csv}{}
{\\\hline\CategoryName\  & \metric}
\end{tabular}

And that also doesn't work, I have a hunch that it's because of the whitespace in the CategoryName field. Any workarounds for this problem without deleting the whitespaces? I can't find a solution in the csvsimple manual.

1
  • 1
    As a side remark: please in the future include any and all error messages that you get from the compilation. Don't just say "it doesn't work". The error message you would've included for your question should be something like ! Incomplete \if; all text was ignored after line 6. <inserted text> \fi l.6 \csvautotabular{cats.csv} . Also, it is great that you included the snipplets, but generally we prefer minimum working examples for diagnosis. Commented May 24, 2016 at 14:15

2 Answers 2

6

You can do it with \csvautotabular, provided you change the category code of & before reading the file.

\begin{filecontents*}{\jobname.csv}
CategoryName,Pageviews
Restaurants,37951
Shopping,22002
Things to do,20067
Nightlife,10612
Gifts,9194
Food Shopping,8655
Useful Stuff,8536
Parenting ,8353
Home,7654
Fitness,6623
Event & Party Planning,6387
Sports,4351
Health & Wellness,4201
Women's Beauty,3807
Pets,2923
Vehicles,2492
Male Grooming,2339
Hotels & Rentals ,2332
Charities,364
\end{filecontents*}

\documentclass{article}
\usepackage{csvsimple}

\begin{document}

\csvautotabular[before reading={\catcode`&=12}]{\jobname.csv}

\end{document}

enter image description here

2
  • This is the better solution; though I do wonder why setting the catcode for & is not the default. Commented May 24, 2016 at 14:43
  • @WillieWong I don't think it's desirable; anyway, this won't work with \csvreader.
    – egreg
    Commented May 24, 2016 at 14:44
6

The problem is the ampersand character &. Edit your CSV file to replace all instances of & by \& or by the text string and solves the problem.


The ampersand is a special character to delineate fields in tabular and array environments. To access it you need to escape it. The csvsimple package doesn't do any sanity checks on your csv data: it reads the data and wraps it up in appropriate LaTeX code for display and use. What is in your csv file is read verbatim.

You must log in to answer this question.

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