我正在使用tabularx
这个解决方案:https://tex.stackexchange.com/a/12712根据内容大小和换行符在可变列宽中实现右对齐。
问题是X | X
缺少列之间的边框:
\documentclass{article}
\usepackage{tabularx} %% tables with auto size
\usepackage{array} %% tables content alignment
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\begin{document}
\begin{center}
\begin{tabularx}{\textwidth}{| X | X | R{2cm} | R{2cm} |}
\hline
Column1 & Column2 & Column3 & Column4 \\ \hline
a & Some Value & This is a very long right-aligned text that should break automatically & This is a very long right-aligned text that should break automatically \\ \hline
b & Some Value & Shorter right-aligned text & Shorter right-aligned text \\ \hline
\end{tabularx}
\end{center}
\end{document}
答案1
\multicolumn{1}{c}
为了回答评论中提出的关于标题的问题,您可以使用或仅仅使用 覆盖右对齐,\centering
因为所有列都是p
(或等效地,X
)列所以是 parboxes。
\documentclass{article}
\usepackage{tabularx} %% tables with auto size
\usepackage{array} %% tables content alignment
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\begin{document}
\begin{center}
\setlength\extrarowheight{2pt}
\begin{tabularx}{\textwidth}{| X | X | R{2cm} | R{2cm} |}
\hline
\centering\bfseries
Column1 &
\centering\bfseries
Column2 &
\centering\bfseries
Column3 &
\centering\bfseries
Column4 \tabularnewline \hline
a & Some Value & This is a very long right-aligned text that should break automatically & This is a very long right-aligned text that should break automatically \\ \hline
b & Some Value & Shorter right-aligned text & Shorter right-aligned text \\ \hline
\end{tabularx}
\end{center}
\end{document}