我正在使用 ACM 双列模板撰写一篇论文,我有一个表格,我想将其仅容纳一列,为此,我想将单元格内的文本拆分为多行。我有以下代码段:
\documentclass{paper}
\begin{document}
\begin{table}[thb]
\centering
\begin{tabular}{|l|c|l|} \hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\ \hline
This is a \\very long line \\of text & Short text & Another long \\line of text \\ \hline
$\pi$ & 1 in 5& Common in math\\
\hline\end{tabular}
\end{table}
\end{document}
但是,它给我的输出不太正确,如下所示。
首先,最后一列文本的第二部分被推入第一列。然后,最后一列的边框也不完整。知道如何将表格单元格中的文本拆分为多行吗?
答案1
包裹tabularx
是你的朋友:
\documentclass[twocolumn]{paper}
\usepackage{tabularx}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\begin{document}
\begin{table}
\centering
\begin{tabularx}{\linewidth}{|L|c|L|}
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\
\hline
This is a very long line of text & Short text & Another long line of text \\
\hline
$\pi$ & 1 in 5& Common in math\\
\hline
\end{tabularx}
\end{table}
\end{document}
答案2
如果要控制单元格中的换行符,可以使用\makecell
同名包中的命令。此外,它还具有向单元格添加一些垂直填充的工具:
\documentclass{paper}
\usepackage{array, makecell} %
\begin{document}
\begin{table}[thb]
\centering\renewcommand\cellalign{lc}
\setcellgapes{3pt}\makegapedcells
\begin{tabular}{|l|c|l|} \hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\ \hline
\makecell{This is a \\very long line \\of text} & Short text &\makecell{ Another long \\line of text} \\ \hline
$\pi$ & 1 in 5& Common in math\\
\hline\end{tabular}
\end{table}
\end{document}
答案3
错误的列对齐是由于&
源代码中缺少列分隔符 ( ) 造成的,可以轻松修复。这还可以修复垂直线断裂的问题。
\begin{table}[thb]
\centering
\begin{tabular}{|l|c|l|}
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\ \hline
This is a & & \\ % <===== note the empty cells in this line
very long line & Short text & Another long \\
of text & & line of text\\ \hline % <===== and in this
$\pi$ & 1 in 5 & Common in math \\ \hline
\end{tabular}
\end{table}
一种不太手动的方法是使用p
列类型,但您必须指定列宽并且 LaTeX 将为您进行换行,但您的最后一个单元格可能也会断开:
\begin{table}[thb]
\centering
\begin{tabular}{|p{1.8cm}|c|p{2cm}|}
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\ \hline
This is a very long line of text & Short text & Another long line of text \\ \hline
$\pi$ & 1 in 5 & Common in math \\ \hline
\end{tabular}
\end{table}
或者您可以使用包。在您的序言中multirow
加载{和之间的任何地方,然后您可以执行以下操作:\usepackage{multirow}
\documentclass{paper}
\begin{document}
\begin{table}[thb]
\centering
\begin{tabular}{|l|c|l|}
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} \\ \hline
\multirow{3}{*}{\parbox{1.8cm}{This is a very long line of text}} & & \multirow{3}{*}{\parbox{2cm}{Another long line of text}} \\
& Short text & \\
& & \\ \hline
$\pi$ & 1 in 5 & Common in math \\ \hline
\end{tabular}
\end{table}
请注意,这会使列垂直居中对齐。\parbox{length}
定义何时应断开文本。