Generate LaTeX tables from CSV files (Excel)

Besides various online services and scripts, there are several LaTeX packages that generate tables directly from CSV (comma separated value) files. The advantage is everything is in the tex-file in one place and one doesn’t have to switch back and forth between website/script and LaTeX when changes are made. The drawback clearly is their limited flexibility or high complexity for sophisticated tables.

Note, I used the following few lines of code to generate a simple CSV file using LaTeX. All examples assume the existence of the file “scientists.csv”. Just copy the code into a tex-file and typeset.

\documentclass{minimal}
\begin{filecontents*}{scientists.csv}
name,surname,age
Albert,Einstein,133
Marie,Curie,145
Thomas,Edison,165
\end{filecontents*}

The star suppresses additional information on the file creation from being added.

Let’s start with a simple package.

 
Package csvsimple

Here is a very basic example. Elements of the first row are considered column titles. To separate them from the table content, a horizontal line is automatically added in between.

\documentclass{article}
\usepackage{csvsimple}
\begin{document}
\csvautotabular{scientists.csv}
\end{document}

The command csvreader provides a better control of the column style, titles and content, but makes things slightly more complicated.

Here is an example:

\documentclass{article}
\usepackage{csvsimple}
\begin{document}
\csvreader[tabular=|l|l|c|,
	table head=\hline & Name & Age\\\hline,
	late after line=\\\hline]%
{scientists.csv}{name=\name,surname=\surename,age=\age}%
{\thecsvrow & \firstname~\name & \age}%
\end{document}

The first part of the optional argument controls the alignment of the content per column (tabular). The second sets the column titles and adds a horizontal line before and after them (table head). Finally, another horizontal line is added to the end of the table (late after line). Furthermore, “commands” are defined for every column using the column title from the CSV file (name, surname and age). These commands allow reordering and combining column content. The command thecsvrow is a row counter and therefore an easy way to enumerate the rows.

Here is the complete package documentation.

 
Package pgfplotstable

A more flexible package is pgfplotstable (package documentation). It allows generating tables from different data files types. However, we will only consider CSV files here.

Again, an optional argument serves to customize what the table looks like, using key-value-pairs. Here is a minimal example with the file generated earlier. A simple example without anything special is quite complicated:

\documentclass{article}
\usepackage{pgfplotstable}
\begin{document}
\pgfplotstabletypeset[
	col sep=comma,
	string type,
	columns/name/.style={column name=Name, column type={|l}},
	columns/surname/.style={column name=Surname, column type={|l}},
	columns/age/.style={column name=Age, column type={|c|}},
	every head row/.style={before row=\hline,after row=\hline},
	every last row/.style={after row=\hline},
	]{scientists.csv}
\end{document}

One of the things that makes this package interesting is, it supports multicolumn.

\documentclass{article}
\usepackage{pgfplotstable}
\begin{document}
\pgfplotstabletypeset[
	col sep=comma,
	string type,
	every head row/.style={%
		before row={\hline
			\multicolumn{2}{c}{Full Name} & \\
		},
		after row=\hline
	},
	every last row/.style={after row=\hline},
	columns/name/.style={column name=Name, column type=l},
	columns/surname/.style={column name=Surname, column type=l},
	columns/age/.style={column name=Age, column type=c},
	]{scientists.csv}
\end{document}

Furthermore, the package allows generation of multi-page tables with longtable (package documentation) with pgfplotstable (see the package documentation for more details).

 
The csvsimple as well as the pgfplotstable package documentations are both comprehensive and very nicely formatted. It seems, the authors put in quite a bit of effort writing them. Check it out!

 
Further packages and other approaches

Other packages that I will not discuss here include:


Correct total number of pages in beamer presentations with backup slides

While writing a presentation with beamer it may be convenient to have some backup/appendix slides ready as a support for answers to potential questions. By default, beamer will count the total number of slides, including the backup slides at the end of the presentation, leading to a wrong number of total slides intended for presentation.

The package appendixnumberbeamer solves the problem through the \appendix command which marks the end of the presentation and resets the page number counter. The total number of slides will be the page number of the last slide before \appendix.

\usepackage{appendixnumberbeamer}
%Presentation slides
\appendix
%Backup slides

Here is a minimal example to illustrate the result.

\documentclass{beamer}
\usepackage{appendixnumberbeamer}
\setbeamertemplate{footline}[page number]
\newcommand{\myframe}[1]{%
	\begin{frame}
		\begin{center}
			\Large #1 slide \insertframenumber/\inserttotalframenumber\\
			Page number \thepage/\inserttotalframenumber
		\end{center}
	\end{frame}
}
\begin{document}
\myframe{Presentation}
\myframe{Presentation}
\appendix
\myframe{Appendix/backup}
\myframe{Appendix/backup}
\end{document}

The documentation for the package is sparse, but there is not that much to be said. For those interested, the package description can be found in the header of the package (style file) itself. In case your distribution does not include the package, download the style file and place it into your project directory.

Ps. I used the following few lines of code in the preamble to print the handouts “4 on 1″:

\usepackage{pgfpages}
\pgfpagesuselayout{4 on 1}[a4paper, landscape, border shrink=5mm]
\pgfpageslogicalpageoptions{1}{border code=\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{2}{border code=\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{3}{border code=\pgfusepath{stroke}}
\pgfpageslogicalpageoptions{4}{border code=\pgfusepath{stroke}}


List of symbols or abbreviations (nomenclature)

Printing a list of abbreviations or symbols is one of these things (like so many) LaTeX provides a very simple and elegant solution for. The nomencl package implements a few basic commands to do that.

 
First load the package in the preamble. The makenomenclature command is required for the generation of the nomenclature file (.nlo). Commenting it out is a convenient way to “switch it off”.

\usepackage{nomencl}
\makenomenclature

Next, add abbreviations together with their description or long form to your document. Ideally, this is done immediately after an abbreviation is mentioned for the first time.

\nomenclature{Fig.}{Figure}
\nomenclature{$A_i$}{Area of the $i^{th}$ component}

This command has an optional argument which provides control over the order of the entries. Consider the following example:

I want $\beta$\nomenclature{$\beta$}{The second letter of the greek alphabet} to be listed after $\alpha$\nomenclature{$\alpha$}{The first letter of the greek alphabet}

Makeindex, the command that generates the list of abbreviations (see below), will automatically sort the entries. Therefore, \alpha and \beta will appear in an “alphabetic” order. To change this order manually, one can use a sorting prefix (optional argument), the simplest would just be consecutive numbers, and the symbols will be sorted accordingly.

I want $\beta$
\nomenclature[2]{$\beta$}{The second letter of the greek alphabet}
to be listed after $\alpha$
\nomenclature[1]{$\alpha$}{The first letter of the greek alphabet}

Linebreaks were added for presentation purposes only.

The following command prints the abbreviation/symbol list at the corresponding position of the document.

\printnomenclature

To control the distance between the symbol or abbreviation and the explaining text use the optional distance argument.

\printnomenclature[5em]

To change the name of the list use

\renewcommand{\nomname}{List of Symbols}

Similar to a glossary or bibliography, the document is typesetted once (latex). Next, the nomenclature is generated using makeindex. Finally, the document is typesetted again, adding the nomenclature to it.

latex filename.tex
makeindex filename.nlo -s nomencl.ist -o filename.nls
latex filename.tex

The makeindex command takes the nomenclature file (.nlo), the style file (nomencl.ist) and the name of the output file (.nls) as input arguments.

 
Complete code of a working example and its output

\documentclass{article}
\usepackage{nomencl}
\makenomenclature
\renewcommand{\nomname}{Time Zones}
\begin{document} 
UTC\nomenclature{UTC}{Coordinated Universal Time} is 3 hours behind ADT\nomenclature{ADT}{Atlantic Daylight Time} and 10 hours ahead of EST\nomenclature{EST}{Eastern Standard Time}.
\printnomenclature
\small\hfill Created by http://texblog.org
\end{document}

Note, to save some typing, you can define your own nomenclature command that prints the symbol/abbreviation and generates a list entry at the same time.

\newcommand*{\nom}[2]{#1\nomenclature{#1}{#2}}
...
\nom{EST}{Eastern Standard Time}

Refer to the nomencl package documentation for more details.


Writing a CV in LaTeX

Writing my curriculum in LaTeX was a task that has been on my TODO-list for quite a while. I liked the style of my Word-written CV and I believed it would take hours to come up with a reasonable CV in LaTeX. Nevertheless, I recently sat down, began writing, and after not too long, I came up with a presentable result that I would like to share.

A complete minimal example can be found at the end of this post.

The Title

In order to even spacing all around, we change the page margins to 3cm using the geometry package. We further make use of the standard article maketitle command, printing the person’s name (title field) and e-mail address (author field).

\documentclass[10pt]{article}
\usepackage[margin=3cm]{geometry}
\title{\bfseries\Huge Tom T. Thurnherr}
\author{texblog+cv@gmail.com}
\date{}
\begin{document}
\maketitle
\end{document}

In case you prefer to add a photo to your CV, try the following slightly more complex code, using minipage:

\documentclass[10pt]{article}
\usepackage[margin=3cm]{geometry}
\title{\bfseries\Huge Tom T. Texblog}
\author{texblog+cv@gmail.com}
\date{}
\begin{document}
\begin{minipage}{0.65\textwidth}
\begingroup
\let\center\flushleft
\let\endcenter\endflushleft
\maketitle
\endgroup
\end{minipage}
\begin{minipage}{0.3\textwidth}
\flushright{\rule{3.5cm}{4.5cm}}
\end{minipage}
\end{document}

Address and Personal Information

We use minipage again to split the page into two parts, one for the address and the second for some personal information if that’s required. Straight forward.

\begin{minipage}[ht]{0.48\textwidth}
Main Road 25\\
City 12345\\
State of Sabotage
\end{minipage}
\begin{minipage}[ht]{0.48\textwidth}
Nonlandian\\
January 3rd, 2020\\
+12 34 56 789
\end{minipage}

The space between the title and the address is just about right. To add more space, use:

\vspace{2em}

The Content

After the cosmetics, we now add the actual content. We use the standard article section with a star to omit numbering. Sections may include: Objective (of the CV), Professional Experience, Education, Languages, Publications, Programming Languages, etc. We will show a few examples here, the structure is always the same.

Let’s first prepare the content with some code in the preamble. We use the tabular environment to divide the page into two columns, a small column for the year/title and a wide column for the description. In order to minimize typing, we define two new columntypes in the preamble, “L” and “R” as well as a thin light-gray line in between, \VRule.

\usepackage{array, xcolor}
\definecolor{lightgray}{gray}{0.8}
\newcolumntype{L}{>{\raggedleft}p{0.14\textwidth}}
\newcolumntype{R}{p{0.8\textwidth}}
\newcommand\VRule{\color{lightgray}\vrule width 0.5pt}

Now we can start creating content sections using the tabular environment as follows:

\section*{Heading}
\begin{tabular}{L!{\VRule}R}
2012&Some text\vspace{5pt}\\
2011&Some other text\\
\end{tabular}

For better readability, we add small vertical spaces between rows in the tabular.

Education

Let’s start by looking at the example with education. We highlighted the parts in bold which are most recent or most important.

\section*{Education}
\begin{tabular}{L!{\VRule}R}
2005--2007&{\bf MSc in Computer Science, Great University, Country.}\vspace{5pt}\\
2001--2005&BSc in Life Science, Great University, Country.\\
\end{tabular}

Languages

Here, we use the left column for the language and the right column for the level of proficiency.

\section*{Languages}
\begin{tabular}{L!{\VRule}R}
Klingon&Mother tongue\\
{\bf English}&{\bf Fluent}\\
French&Fluent (DELF 2010)\\
Japanese&Fair\\
\end{tabular}

Professional Experience

\usepackage{lipsum}
...
\section*{Professional Experience}
\begin{tabular}{L!{\VRule}R}
2011--today&{\bf Work at company XY.}\\
&\lipsum[66]\vspace{5pt}\\
2008--2010&{\bf Trainee at company ZY.}\\
&\lipsum[66]\\
\end{tabular}


Publications

We use the bibentry package to generate an inline list of publications. The references are stored in a bibtex file.

\usepackage{bibentry}
...
\bibliographystyle{plain}
\nobibliography{publication.bib}
\section*{Publications}
\begin{tabular}{L!{\VRule}R}
2006&\bibentry{knuth2006art}\vspace{5pt}\\
1968&\bibentry{lamport1986latex}\\
\end{tabular}

Minimal Example CV

\documentclass[10pt]{article}
\usepackage{array, xcolor, lipsum, bibentry}
\usepackage[margin=3cm]{geometry}

\title{\bfseries\Huge Tom T. Texblog}
\author{texblog+cv@gmail.com}
\date{}

\definecolor{lightgray}{gray}{0.8}
\newcolumntype{L}{>{\raggedleft}p{0.14\textwidth}}
\newcolumntype{R}{p{0.8\textwidth}}
\newcommand\VRule{\color{lightgray}\vrule width 0.5pt}

\begin{filecontents}{publication.bib}
@article{lamport1986latex,
  title={LaTEX: User's Guide \& Reference Manual},
  author={Lamport, L.},
  year={1986},
  publisher={Addison-Wesley}
}
@book{knuth2006art,
  title={The art of computer programming: Generating all trees: history of combinatorial generation},
  author={Knuth, D.E.},
  volume={4},
  year={2006},
  publisher={addison-Wesley}
}
\end{filecontents}

\begin{document}
\maketitle
\vspace{1em}
\begin{minipage}[ht]{0.48\textwidth}
Main Road 25\\
City 12345\\
State of Sabotage
\end{minipage}
\begin{minipage}[ht]{0.48\textwidth}
Nonlandian\\
January 3rd, 2020\\
+12 34 56 789
\end{minipage}
\vspace{20pt}

\section*{Objective}
Find a job.

\section*{Professional Experience}
\begin{tabular}{L!{\VRule}R}
2011--today&{\bf Work at company XY.}\\
&\lipsum[66]\\
\end{tabular}

\section*{Education}
\begin{tabular}{L!{\VRule}R}
2005--2007&{\bf MSc in Computer Science, Great University, Country.}\vspace{5pt}\\
2001--2005&BSc in Life Science, Great University, Country.\\
\end{tabular}

\section*{Languages}
\begin{tabular}{L!{\VRule}R}
Klingon&Mother tongue\\
{\bf English}&{\bf Fluent}\\
French&Fluent (DELF 2010)\\
Japanese&Fair\\
\end{tabular}

\bibliographystyle{plain}
\nobibliography{publication.bib}

\section*{Publications}
\begin{tabular}{L!{\VRule}R}
2006&\bibentry{knuth2006art}\vspace{5pt}\\
1986&\bibentry{lamport1986latex}\\
\end{tabular}
{\vspace{20pt}\newline\newline
\vspace{20pt}
\scriptsize\hfill Created by http://texblog.org}

\end{document}

Additional Resources

Drop me a comment if you know of other resources and I will add them to the list.

Update

A few days after publishing this post, a vivid discussion took place with lots of interesting CV examples on hackerne.ws.


Counting the total number of…

…sections, chapters, pages, theorems, equations, references, etc. There are numerous potential commands in LaTeX one may consider counting in order to automatically output their total number of appearances in a document. The totcount package provides a simple way to do that.

We will to consider two different cases, single commands (cite, section, chapter, etc.) and environments (equation, align, theorem) which are treated slightly differently. In fact, many environments have their particularities and may therefore need special manipulation. Let’s start with the more consistent case for which the author provided a minimal working example in the package documentation.

 
References (cite)

First, we define a new counter, in this case citenum. Next, we redefine the command cite, increasing the newly defined counter every time the command is called. Finally, we redefine the bibliography title in order to display the total number of references.

Below you will find a code example along with the pdf output:

\documentclass[11pt]{article}
\usepackage{totcount}
\newtotcounter{citenum}
\def\oldcite{}
\let\oldcite=\bibcite
\def\bibcite{\stepcounter{citenum}\oldcite}
\renewcommand\refname{References (\total{citenum})} %For article
%\renewcommand\bibname{} %For book and report
\begin{document}
A few \TeX\ references by Lamport \cite{lamport1986, lamport1987, lamport1994}
\bibliographystyle{plain}
\bibliography{references}
\tiny\hfill Created by http://texblog.org
\end{document}

For simple commands, displaying their total number is relatively straight forward. Let’s have a look at an example where the command defines an environment.

 
Equation

As mentioned before, different environments behave differently and therefore need special handling. As an example, we will now show how to display the total number of equations along with the equation label on the right-hand side of every equation.

There are several ways to do it. In the example below, we use the mathtools package which provides the tag command, allowing to change the equation label. The label change will automatically be reflected when referencing the equations (see pdf output below). For practical reasons and to reduce typing, we implement the command eqn in the preamble. The command takes care of the counters and uses the standard equation environment to display the equation.

\documentclass[11pt]{article}
\usepackage{totcount, mathtools}
\newtotcounter{eqnnum}
\newcommand*{\eqn}[2]{%
	\stepcounter{eqnnum}%
	\stepcounter{equation}%
	\begin{equation}\label{#2}%
		#1\tag{\arabic{equation}/\protect\total{eqnnum}}%
	\end{equation}%
}
\begin{document}
\eqn{f_1(x)=a_1x^2+b_1x+c_1}{eqn:first}
\eqn{f_2(x)=a_2x^2+b_2x+c_2}{eqn:second}
See equation (\ref{eqn:first}) and (\ref{eqn:second}).
\tiny\hfill Created by http://texblog.org
\end{document}

 
Page numbers

See this posts for an example on how to display to the total number of pages in a document, e.g. Page 4 of 65.


Left equation numbering

By default, equation numbers are place on the right side of an equation for any numbered math environment, such as equation, eqnarray, and align. Surprisingly, the equation number position can is changed through the optional documentclass argument leqno:

Left numbering

\documentclass[leqno]{article}

Right numbering (by default and therefore usually skipped):

\documentclass[reqno]{article}

Here is a minimal working example:

\documentclass[a4paper,12pt, leqno]{article}
\usepackage{amsmath}
\begin{document}
\subsubsection*{Equation:}
\begin{equation}
	f(x)=ax^2+bx+c
\end{equation}
\subsubsection*{Align:}
\begin{align}
	f_1(x)&=a_1x^2+b_1x+c_1\\
	f_2(x)&=a_2x^2+b_2x+c_2
\end{align}
\end{document}

Align is part of the amsmath package which was used here because there are several reasons to avoid eqnarray.


Cross-referencing list items

List items of numbered lists (enumerate) can be cross-referenced using the standard \label{} and \ref{} command pair. Cross-referencing description items is not supported by default, but can be done with a few additional lines of code in the preamble.

Enumerate
Ordered or numbered lists are cross-referenced with the label-ref command pair similar to figures, tables or chapters. The label can either be place right after \item or after the item’s text. The cross-reference \ref{} works within and outside the list as shown in the example below.

\documentclass[11pt]{article}
\usepackage{hyperref}
\begin{document}
\begin{enumerate}
	\item \label{itm:first} This is a numbered item
	\item Another numbered item \label{itm:second}
	\item \label{itm:third} Same as \ref{itm:first}
\end{enumerate}
Cross-referencing items \ref{itm:second} and \ref{itm:third}.
\end{document}

Cross-referencing numbered items in lists (enumerate).

Loading the hyperref package, automatically adds links to cross-references and allows navigation to list items by clicking the reference.

Description
By default, items in a description can’t be cross-referenced. LaTeX would just use the number of the section/chapter. SX has a solution with a few lines of additional code in the preamble.

\documentclass[11pt]{article}
\usepackage{enumitem, hyperref}
\makeatletter
\def\namedlabel#1#2{\begingroup
	#2%
	\def\@currentlabel{#2}%
	\phantomsection\label{#1}\endgroup
}
\makeatother
\begin{document}
\begin{description}[style=multiline, labelwidth=1.5cm]
	\item[\namedlabel{itm:rule1}{Rule 1}] Everything is easy with \LaTeX
	\item[\namedlabel{itm:rule2}{Rule 2}] Sometimes it is not that easy\\
		$\to$ \ref{itm:rule1} applies
\end{description}
\end{document}

Cross-referencing description items

The code in the preamble defines a new command namedlabel which produces the name when cross-referencing the item. In the example, the enumitem package is loaded for a correct alignment of multiline items (see documentation for details)

Itemize
Cross-referencing items in unordered lists (bullet items) is not supported and wouldn’t make sense anyway, since individual items don’t have an unique identifier.


Greek letters in text without changing to math mode

You don’t need to change to math mode every time you want to type a greek letter in normal text. Loading the textgreek package allows typesetting greek letters, generally just by adding a text-prefix to the letter name, e.g. for \Delta\beta it would be:

\usepackage{textgreek}
...
\textDelta\textbeta

The letters will adapt to the font style you are using (bold, italics, small capitals, etc.)

Furthermore, the author provides three different font types, cbgreek (default), euler, and anthemisia. The font type can be change through the optional argument, when loading the package:

\usepackage[euler]{textgreek}

The differences are minor for most letters, check the documentation for details.

Complete command list (copied from the documentation):

Commands for greek letters in normal text.

Note, \mu is an exception. Since the textcomp package already provided a command textmu, the author decided to call it textmugreek instead. Use the latter to avoid unexpected results.


Latex page, line and font settings

I was recently asked to write a three page assignment/case study using the following page, line and font settings:

  • Arial, size 12
  • 1.5 line spacing
  • 2.5cm margin all round

Let’s do one by one.

 

Font type and size

Font types are actually a bit of a pain in Latex and so far, I have almost always been using the standard font, Knuth’s Computer Modern. The reason for not using the fonts provided by the system is that Tex and Latex will give the same distinctive look no matter which platform a document was compile on, making the language system independent.

Some fonts are available, including Times Roman, Helvetica and Courier. Arial however is a “non-free-font” from Microsoft and has to be installed manually — I give up, it’s getting late and I tried various things without success, including installation of the Arial font family.

I will go with XeLaTeX using system fonts, nice :-) .

\documentclass[11pt]{article}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{fontspec}
\setmainfont{Arial}
\begin{document}
\blindtext
\end{document}

Another, less clean approach I came across uses Latex with the following two lines added to the preamble:

\renewcommand{\rmdefault}{phv}
\renewcommand{\sfdefault}{phv}

It changes the font family to Helvetica, which is very similar to Arial, but it’s not the same.

The font size is easy, just use the documentclass option:

\documentclass[12pt]{article}

This brings me to the next point on the list above. I will stick to XeLaTeX, but all the examples will perfectly work with LaTeX, assuming you are using Helvetica and not Arial.

 

Linespacing

Basically, 1.5 line spacing is done using the setspace package as follows:

\usepackage{setspace}
\onehalfspacing

Please see my previous post on that topic for more details on line spacing.

 

Setting the margins

If you are lucky enough to require an equal margin on all sides, the geometry package with the margin option will do the trick:

\usepackage[margin=2.5cm]{geometry}

For different margins on every side, the package provides four options: top, left, bottom, right:

\usepackage[top=1.2in, left=0.9in, bottom=1.2in, right=0.9in]{geometry}

See the package documentation for more details.

 

Complete example (XeLaTeX)

\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage{blindtext, fontspec, setspace}
\usepackage[margin=2.5cm]{geometry}
\setmainfont{Arial}
\onehalfspacing
\begin{document}
\blindtext
\end{document}

Customizing font, margins and line spacing.

Please leave me a comment if you know of a simple and nice tutorial on how to install non-free-fonts like Arial. Thanks!


Follow

Get every new post delivered to your Inbox.

Join 316 other followers