2

I am trying to create a table with two different types of rows using a csv file.

The csv looks like this

Data1,Data2,Data3
Caption1,,
Value1,Value2,Value3
Value4,Value5,Value6
Caption2,,
Value8,Value9,Value10
.....

Every caption should use all three columns of the table, so I tried the following code:

\documentclass[a4paper,12pt]{article}
\usepackage{tabularx}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{datatool}
\usepackage{float}
\usepackage{wrapfig}

\begin{document}

\begin{figure}[H]
    \DTLloaddb{Database_Name}{Test.csv}
    \centering
    \begin{tabular}{l c c}
        \toprule
        a & b & c \\
        \midrule
        \DTLforeach{Database_Name}
            {\a=Data1,\b=Data2,\c=Data3}
            {
%-----------------------
                \DTLifnullorempty{\c}{\multicolumn{3}{c}{\a}}{\a & \b & \c}
%-----------------------
                \DTLiflastrow{}{\\}} \\
            \bottomrule
        \end{tabular}
    \end{figure}

    \end{document}

but \multicolumn and & don't work if I use them in the condition. Do you have any idea how I can fix this problem?

2

The cells in a LaTeX tabular are implicitly local groups. This will break many loop macros. A workaround is to compose the table in a token register first using the loop marco and output the token register to set the table afterwards:

\documentclass[a4paper,12pt]{article}
\usepackage{booktabs}
\usepackage{datatool}
\newtoks\tabletoks

\begin{document}
\begin{figure}
    \DTLloaddb{Database_Name}{abc.csv}
    \centering
    \makeatletter
    \tabletoks={%
      \begin{tabular}{l c c}
      \toprule
      a & b & c \\
      \midrule
    }%
    \DTLforeach{Database_Name}{%
      \a=Data1,\b=Data2,\c=Data3%
    }{%
      \DTLifnullorempty{\c}{%
        \protected@edef\x{%
          \noexpand\multicolumn{3}{c}{\a}%
        }%
      }{%
        \protected@edef\x{\a & \b & \c}%
      }%
      \tabletoks\expandafter{\the\expandafter\tabletoks\x\\}%
    }%
    \tabletoks\expandafter{%
      \the\tabletoks
      \bottomrule
      \end{tabular}%
    }%
    \the\tabletoks
  \end{figure}
\end{document}

Result

\protected@edef is used to expand the macros \a, \b, \c, before putting them into the token register.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.