我想让 Latex 自动在单元格中放置新行,以使表格适合页面宽度,这可能吗?
例如,此代码将显示表格,但表格不适合页面宽度:
\usepackage{tabularx}
\begin{tabular*}{\textwidth}{c| @{\extracolsep{\fill}} c|c}
\hline
This is a very long table and cannot fit in the page width & another long words & more long words \\
\hline
\hline
example & example & example of a lot of text here so this should also go to multiple lines in this cell \\
\hline
A & B & C \\
\hline
\end{tabular*}
答案1
使用tabularx
和X
说明符。该booktabs
包允许在水平线周围设置不太紧密的设置:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier}%
\usepackage{heuristica}
\usepackage{geometry}
\usepackage{array}
\usepackage{tabularx}
\usepackage{caption}
\begin{document}
\begin{table}[!htbp]
\centering%
\caption{}
\begin{tabularx}{\linewidth}{XXX}
\toprule
This is a very long table and cannot fit in the page width & another long words & more long words \\
\midrule
\midrule
example & example & example of a lot of text here so this should also go to multiple lines in this cell \\
\midrule
A & B & C \\
\bottomrule
\end{tabularx}
\end{table}
\end{document}
如果希望单元格中有中心线,可以使用 定义新的列类型array package
,例如:
\newcolumntype{C}{>{\centering\arraybackslash}X}
如果您希望多行单元格垂直居中,则必须使用以下命令重新定义 X 类型:
\renewcommand{\tabularxcolumn}[1]{m{#1}}%
例子:
如果您想要垂直线(不推荐)与水平线相交,则不能使用书形标签。但是,您仍然可以使用包中的和来获得不同粗细的水平规则\Xhline
。\Xcline
但这样一makecell
来,您就会失去书形标签在水平线周围引入的补充垂直空间。Makecell 有一个命令可以执行此操作(\makegapedcells
),但它似乎不适用于X
单元格。因此,必须使用cellspace
包,它定义了单元格顶部与上方单元格底部之间以及单元格底部与下方单元格顶部之间的最小垂直间距。以下是示例:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier}%
\usepackage{heuristica}
\usepackage{geometry}
\usepackage{booktabs}
\usepackage{array}
\usepackage{tabularx}
\usepackage{caption}
\renewcommand{\tabularxcolumn}[1]{m{#1}}%
\newcolumntype{C}{>{\centering\arraybackslash}X}
\usepackage{makecell}
\usepackage{cellspace}
\setlength\cellspacetoplimit{4pt}
\setlength\cellspacebottomlimit{4pt}
\addparagraphcolumntypes{X}
\begin{document}
\begin{table}[!htbp]
\centering%
\caption{}
\begin{tabularx}{\linewidth}{S{X}|S{X}|S{X}}
\Xhline{0.8pt}
This is a very long table and cannot fit in the page width & another long words & more long words \\
\hline\hline
example & example & example of a lot of text here so this should also go to multiple lines in this cell \\
\hline
A & B & C \\
\Xhline{0.8pt}
\end{tabularx}
\end{table}
\end{document}
答案2
无需任何额外的软件包,你可以这样做:
\documentclass{article}
\begin{document}
\begin{table}[!htbp]
\centering%
\caption{}
\begin{tabular}{p{\dimexpr0.333\textwidth-2\tabcolsep-\arrayrulewidth\relax}|
p{\dimexpr0.333\textwidth-2\tabcolsep-\arrayrulewidth\relax}|
p{\dimexpr0.333\textwidth-2\tabcolsep-\arrayrulewidth\relax}
}
\hline
This is a very long table and cannot fit in the page width & another long words & more long words \\
\hline
\hline
example & example & example of a lot of text here so this should also go to multiple lines in this cell \\
\hline
A & B & C \\
\hline
\end{tabular}
\end{table}
\end{document}
如果要垂直居中对齐,请替换p
为m
。