循环时表格损坏

循环时表格损坏

以下是 MWE:

\documentclass{article}
\usepackage{pgffor, geometry, tabu, booktabs}
\geometry{
  a4paper, 
  portrait, 
  margin=1in
}
\begin{document}

Here is creating the table using a loop\\[10pt]

    \foreach \n in {Feb, Mar, April is the best month}{
      \begin{tabu}{X[-1] X}
        \n & \foreach \m in {0,...,30}{\framebox(9,9){} }\\ \midrule
      \end{tabu}
}
\vskip 20pt
Here is creating table one row at a time\\[10pt]

      \begin{tabu}{X[-1] X}
        Feb & \foreach \n in {0,...,30}{\framebox(9,9){} }\\ \midrule
        Mar & \foreach \n in {0,...,30}{\framebox(9,9){} }\\ \midrule
        April is the best month & \foreach \n in {0,...,30}{\framebox(9,9){} }\\ \midrule
      \end{tabu}
\end{document}

循环中的表格已损坏---没有列对齐。

如何将循环中的表设置为没有循环的表?

答案1

这是表格中的 Foreach 循环,插入缺少的末端组,但这是针对此特定情况的代码:

\documentclass{article}

\usepackage{pgffor, geometry, tabu, booktabs, etoolbox}

\geometry{
  a4paper,
  portrait,
  margin=1in
}

\begin{document}

\newcommand{\tablecontents}{}
\foreach \n in {Feb, Mar, April is the best month} {
\xappto\tablecontents{\n &}
\foreach \m in {0,...,30}{\gappto\tablecontents{\framebox(9,9){} } }
\gappto\tablecontents{\\ \midrule}
}

Here is creating the table using a loop\\[10pt]

\begin{tabu}{X[-1] X}
\tablecontents
\end{tabu}

\end{document}

示例输出

要在每个框中输入日期,\m需要小心扩展,因此内循环线变成

\foreach \m in {0,...,30}{\xappto\tablecontents{\noexpand\framebox(9,9){\m} } }

\xappto扩展其内容,您需要获取的值\m,但扩展\framebox需要稍后进行。 \gappto不扩展。

答案2

在制作表格之前,您必须先构建表格主体。以下是使用 的实现xparse

\documentclass{article}
\usepackage{geometry, tabularx, booktabs}
\usepackage{xparse}
\geometry{
  a4paper, 
  portrait, 
  margin=1in
}

\ExplSyntaxOn
\seq_new:N \l__deshmukh_monthtable_in_seq
\seq_new:N \l__deshmukh_monthtable_out_seq

\cs_new_protected:Nn \__deshmukh_printmonth:n
 {
  { #1 } & \prg_replicate:nn { 30 } { \framebox(9,9){} ~ }
 }

\NewDocumentCommand{\monthtable}{m}
 {
  \seq_set_split:Nnn \l__deshmukh_monthtable_in_seq {,} { #1 }
  \seq_clear:N \l__deshmukh_monthtable_out_seq
  \seq_map_inline:Nn \l__deshmukh_monthtable_in_seq
   {
    \seq_put_right:Nn \l__deshmukh_monthtable_out_seq
     { \__deshmukh_printmonth:n { ##1 } }
   }
  \noindent
  \begin{tabularx}{\textwidth}{l>{\raggedright\arraybackslash}X}
  \toprule
  \seq_use:Nn \l__deshmukh_monthtable_out_seq { \\ \midrule }
  \\ \bottomrule
  \end{tabularx}
 }
\ExplSyntaxOff

\begin{document}

\monthtable{Feb,Mar,April is the best month}

\end{document}

在此处输入图片描述

相关内容