我想基於逗號分隔的資料建立一個表,如下所示:
\documentclass{article}
\usepackage{pgffor}
\usepackage{multirow}
\usepackage{float}
\newcommand{\cases}{a , b}
\newcommand{\repetir}{
\foreach \case in {\cases}{
\case & & & & & & & & & & & & & & & \\\hline
}
}
\begin{document}
\begin{table}[H]
\centering
\scriptsize
\begin{tabular}{ | p{4cm} | p{3cm} |l| l|l|l| l | l | l | l | l| l | l | l | l | p{3cm} | }
\hline
\multirow{3}{*}{Case name} & \multirow{3}{*}{Description} & \multicolumn{14}{c|}{Further Details} \\\cline{3-16}
& & \multicolumn{3}{c|}{O} & \multicolumn{3}{c|}{A} & \multicolumn{2}{c|}{F} & \multicolumn{2}{c|}{B} & & \multirow{2}{*}{G} & \multirow{2}{*}{C} & \multirow{2}{*}{Other} \\ \cline{3-13}
& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 \\ \hline
\repetir
\end{tabular}
\end{table}
\end{document}
但我總是收到錯誤:
Extra } or forgotten \endgroup \repetir.
我怎樣才能做到這一點?
答案1
您不能\foreach
從一個表格單元格開始並在另一個表格單元格中結束。
\documentclass{article}
\usepackage[a4paper,landscape]{geometry}
\usepackage{multirow}
\usepackage{xparse}
% a command for doing the repetitive things:
% 1. open center, 2. choose the font size,
% 3. start the tabular, 4. print the header
% Next the command processes the argument and
% ends the job
\NewDocumentCommand{\chungeltable}{m}
{%
\begin{center}\scriptsize
\begin{tabular}{ | p{4cm} | p{3cm} | *{13}{l|} p{3cm} | }
\hline
\multirow{3}{*}{Case name} &
\multirow{3}{*}{Description} &
\multicolumn{14}{c|}{Further Details} \\
\cline{3-16}
& & \multicolumn{3}{c|}{O} & \multicolumn{3}{c|}{A} & \multicolumn{2}{c|}{F} &
\multicolumn{3}{c|}{B} & \multirow{2}{*}{G} & \multirow{2}{*}{C} & \multirow{2}{*}{Other} \\
\cline{3-13}
& & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & & & \\ \hline
\chungeltablebody{#1}
\end{tabular}
\end{center}
}
\ExplSyntaxOn
\NewDocumentCommand{\chungeltablebody}{m}
{
% clear the variable that will contain the table body
\tl_clear:N \l_tmpa_tl
% for each item in the comma separated list
\clist_map_inline:nn { #1 }
{
% add the item followed by the necessary number of &'s
% to the variable containing the table body
\tl_put_right:Nn \l_tmpa_tl { ##1 & & & & & & & & & & & & & & & \\\hline }
}
% deliver the table body
\tl_use:N \l_tmpa_tl
}
\ExplSyntaxOff
\begin{document}
\chungeltable{a,b}
\end{document}
關鍵是\clist_map_inline:nn
;第一個參數中的每個項目都會傳遞給#1
第二個參數中的程式碼。
由於我們位於定義主體中,#1
因此應該成為##1
,因為#1
它是我們定義的巨集的實際參數。