抽象出“表头字体为粗体”

抽象出“表头字体为粗体”

假设我希望我的表格具有以下外观:

所需的桌子布局

我可以这样做:

\documentclass{memoir}
\usepackage[table]{xcolor}

\begin{document}

\begin{table}[h!]
    \centering
    \rowcolors{2}{green!15}{gray!5}
    \begin{tabular}{ll}
        \rowcolor{green}
        \textbf{Who} & \textbf{Dynasty}\\
        Djet & First Dynasty\\
        Neferkare VII & Ninth Dynasty \\
        Bakenranef & Twenty-Fourth Dynasty\\
    \end{tabular}
    \caption{Other pharaohs and their dynasties}
\end{table}

\end{document}

但我希望文档中的所有表格都具有这种外观,而直接在每个表格中执行此操作似乎不必要地容易出错、耗费大量人力,并且(取决于文档的大小)难以更改。所以我想抽象出表格样式。类似于:

\documentclass{memoir}
\usepackage[table]{xcolor}
\usepackage{xparse}

\begin{document}

\NewDocumentEnvironment{BobTable}{mm}{
    \begin{table}[h!]
        \centering
        \rowcolors{2}{green!15}{gray!5}
        \begin{tabular}{#1}
            \rowcolor{green}
} {
        \end{tabular}
        \caption{#2}
    \end{table}
}

\begin{BobTable}{ll}{Other pharaohs and their dynasties}
    \textbf{Who} & \textbf{Dynasty}\\
    Djet & First Dynasty\\
    Neferkare VII & Ninth Dynasty\\
    Bakenranef & Twenty-Fourth Dynasty\\
\end{BobTable}

\end{document}

就目前而言,这很好,但请注意,我仍然直接将标题行的各个部分加粗。我还想将其抽象出来——“第一行的各个部分始终加粗”——所以我可以这样做:

\begin{BobTable}{ll}{Other pharaohs and their dynasties}
    Who & Dynasty\\
    Djet & First Dynasty\\
    Neferkare VII & Ninth Dynasty\\
    Bakenranef & Twenty-Fourth Dynasty\\
\end{BobTable}

到目前为止,我还没能想出办法。能否对我的想法进行一些小的调整,或者采用一些根本不同的方法,让我也能将其抽象出来?谢谢。

答案1

问题在于单元格开头缺少钩子,因此使用标准列类型会比较困难。使用新列类型可以这样做,例如:

\documentclass{memoir}
\usepackage[table]{xcolor}
\usepackage{xparse}
\usepackage{array}


\ExplSyntaxOn
\tl_new:N\g__bob_tabcellhook
\newcolumntype{\bobl}{>{\g__bob_tabcellhook}l}
\cs_new:Nn\__bob_tabcell_hook_set:
 {
    \tl_gset:Nn \g__bob_tabcellhook {}
 }
\NewDocumentEnvironment{BobTable}{mm}
  {
    \begin{table}[h!]
        \centering
        \rowcolors{2}{green!15}{gray!5}
        \tl_gset:Nn \g__bob_tabcellhook {\bfseries}
        \begin{tabular}{#1<{\__bob_tabcell_hook_set:}}
            \rowcolor{green}
  } 
  {
        \end{tabular}
        \caption{#2}
    \end{table}
  }
\ExplSyntaxOff
\begin{document}
\begin{BobTable}{\bobl\bobl}{Other pharaohs and their dynasties}
    Who & Dynasty\\
    Djet & First Dynasty\\
    Neferkare VII & Ninth Dynasty\\
    Bakenranef & Twenty-Fourth Dynasty\\
\end{BobTable}

\begin{BobTable}{\bobl\bobl}{Other pharaohs and their dynasties}
    Who & Dynasty\\
    Djet & First Dynasty\\
    Neferkare VII & Ninth Dynasty\\
    Bakenranef & Twenty-Fourth Dynasty\\
\end{BobTable}
\end{document}

在此处输入图片描述

相关内容