表格:將一個表格的維度與另一個表格結合起來

表格:將一個表格的維度與另一個表格結合起來

tabular將列寬設定為所有行中最寬的元素。

是否可以設定兩個或多個單獨的tabulars 來考慮彼此的列寬並選擇其中最大的一個?

例如,如果我tabular用附加段落文字打破 a 並希望繼續表格,就好像它是longtable交叉到下一頁一樣(相同的列寬,可能會重申標題),這可能嗎?

答案1

這個想法是創建一堆特殊的列類型,這樣每次該列類型出現在表格中時,它總是具有相同的寬度。這需要文件運行 2 次,其中第一次運行中計算的寬度保存在 aux 檔案中。

注意:如果您想要讓列更窄,您將需要刪除 aux 檔案或至少註解掉 \AtEndDocument。

\documentclass{article}
\usepackage{array}

\newsavebox{\tempbox}% \box0 etc. used

\makeatletter
\newcommand{\saveWidth}[1]% #1=column name (A,B,...)
{\immediate\write\@auxout{\string\initWidth{#1}{\the\csname Width#1\endcsname}}}

\newcommand{\initWidth}[2]% #1=column name (A,B,...), #2=the width
{\@ifundefined{Width#1}{}{\global\csname Width#1\endcsname=#2\relax}}
\makeatother

\newlength{\WidthA}% one for each column type
\newlength{\WidthB}
\newlength{\WidthC}

\AtEndDocument{\saveWidth{A}\saveWidth{B}\saveWidth{C}}

\newcolumntype{A}{>{\savebox{\tempbox}\bgroup}{l}<{\egroup%
  \ifdim\wd\tempbox>\WidthA \global\WidthA=\wd\tempbox\fi%
  \makebox[\WidthA][l]{\usebox\tempbox}}}

\newcolumntype{B}{>{\savebox{\tempbox}\bgroup}{c}<{\egroup%
  \ifdim\wd\tempbox>\WidthB \global\WidthB=\wd\tempbox\fi%
  \makebox[\WidthB][c]{\usebox\tempbox}}}

\newcolumntype{C}{>{\savebox{\tempbox}\bgroup}{r}<{\egroup%
  \ifdim\wd\tempbox>\WidthC \global\WidthC=\wd\tempbox\fi%
  \makebox[\WidthC][r]{\usebox\tempbox}}}

\begin{document}
\noindent\begin{tabular}{ABC}
left & center & right\\
wide left & wide center  & wide right
\end{tabular}

\medskip
Some text here.
\medskip

\noindent\begin{tabular}{ABC}
left & center & right\\
\end{tabular}

\medskip
Some text here.
\medskip

\noindent\begin{tabular}{ABC}
very wide left & very wide center & very wide right\\
\end{tabular}

\end{document}

為了更容易建立新列,我新增了\newcolumnwidth{<name>}{l/c/r}(這本身相當難看)。

\newcommand{\newcolumnwidth}[2]% #1=new column type, #2=l/c/r
{\expandafter\newlength\csname Width#1\endcsname%
 \AtEndDocument{\saveWidth{#1}}%
 \newcolumntype{#1}{>{\savebox{\tempbox}\bgroup}{#2}<{\egroup%
  \ifdim\wd\tempbox>\csname Width#1\endcsname \global\csname Width#1\endcsname=\wd\tempbox\fi%
  \makebox[\csname Width#1\endcsname][#2]{\usebox\tempbox}}}}

\newcolumnwidth{A}{l}
\newcolumnwidth{B}{c}
\newcolumnwidth{C}{r}

答案2

我將遵循的方法與在環境中所做的類似tabbing。您設定定義製表位的第一行,然後設定\kill該行,使其不顯示。後續行將使用這些製表位,而第一行不存在。

在此輸入影像描述

\documentclass{article}

\begin{document}

\noindent
\begin{tabular}{l c r}
  left      & center      &      right \\
  wide left & wide center & wide right
\end{tabular}

\medskip

Some text here.

\medskip

\noindent
\begin{tabular}{l c r}
  \phantom{wide left} &
    \phantom{wide center} & 
    \phantom{wide right} \\[-\normalbaselineskip]% Similar to \kill
  left      & center      &      right
\end{tabular}

\end{document}

上面範例中的「\kill行」將兩個表中最寬的元素放置在 內\phantom,而行的高度則使用表單的換行符號刪除\\[-\normalbaselineskip]

如果要隱藏的內容很高,請使用\hphantom。如果您擔心垂直規則的疊印,請不要使用它們(正如很棒的建議booktabs)或使用以下方法將每個列元素插入「\kill行」中\multicolumn{1}{l}{...} 沒有垂直規則。

相關內容