
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{longtable}
\title{Table Sample}
\author{Nimish Mistry}
\date{July 2017}
\begin{document}
\maketitle
\section{2 column table}
\begin{longtable}{|p{0.5\textwidth}|p{0.5\textwidth}|}
\hline
A & B \\
\hline
\end{longtable}
\section{3 column table}
\begin{longtable}{|p{0.33\textwidth}|p{0.33\textwidth}|p{0.33\textwidth}|}
\hline
A & B & C \\
\hline
\end{longtable}
\section{4 column table}
\begin{longtable}{|p{0.25\textwidth}|p{0.25\textwidth}|p{0.25\textwidth}|p{0.25\textwidth}|}
\hline
A & B & C & D \\
\hline
\end{longtable}
\section{4 column table}
\end{document}
答案1
由於列數不同,垂直線和\tabcolsep
空間的數量也不同,因此在確定列寬時需要考慮垂直線和\tabcolsep
空間的寬度。
請嘗試以下操作:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{array, longtable}% added array, as suggest David in hos comment below
\begin{document}
\begin{longtable}{|*{2}{p{\dimexpr0.5\textwidth-2\tabcolsep-1.5\arrayrulewidth\relax}|}} % calculation of column width
\hline
A & B \\
\hline
\end{longtable}
\begin{longtable}{|*{3}{p{\dimexpr0.333\textwidth-2\tabcolsep-1.33\arrayrulewidth\relax}|}}
\hline
A & B & C \\
\hline
\end{longtable}
\begin{longtable}{|*{4}{p{\dimexpr0.25\textwidth-2\tabcolsep-1.25\arrayrulewidth\relax}|}}
\hline
A & B & C & D \\
\hline
\end{longtable}
\end{document}
編輯: 第一個解決方案計算出的表格寬度錯誤(請參閱下面 David Carlisle 的評論。考慮到這一點,上面的程式碼已相應更正。如下圖所示:
其生成方式為:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{array,longtable}
%-------------------------------------- only for show page layout
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%
\setlength\arrayrulewidth{22pt}
\begin{document}
\begin{longtable}{|*{2}{p{\dimexpr0.5\textwidth-2\tabcolsep-1.5\arrayrulewidth)\relax}|}} % calculation of column width
\hline
A & B \\
\hline
\end{longtable}
\begin{longtable}{|*{3}{p{\dimexpr0.333\textwidth-2\tabcolsep-1.33\arrayrulewidth\relax}|}}
\hline
A & B & C \\
\hline
\end{longtable}
\begin{longtable}{|*{4}{p{\dimexpr0.25\textwidth-2\tabcolsep-1.25\arrayrulewidth\relax}|}}
\hline
A & B & C & D \\
\hline
\end{longtable}
\end{document}
答案2
當您不需要在下一頁的開頭重複表格標題(longtable
套件的核心功能)並且假設表格儲存格中只有短文字(沒有多行段落)時,則不需要手動計算儲存格寬度。您可以在每個單元格中使用\hbox to\hsize
組合的原始構造\hfil
。
\def\ta|{\hbox to\hsize \bgroup \vrule height12pt depth5pt \taA}
\def\taA{\futurelet\next\taB}
\def\taB{\ifx\next\relax\egroup \else \expandafter\taC \fi}
\def\taC#1|{\quad\rlap{#1}\hfil\vrule \taA}
\hrule
\ta |A|B|C|\relax
\hrule
\medskip
\hrule
\ta |A|B|\relax
\hrule
\medskip
\hrule
\ta |A|B|C|D|\relax
\hrule
\bye