\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