
Я использую Kile и пытаюсь научиться с его помощью tabularx
создавать таблицы, которые вписываются в ширину моих страниц.
Однако у меня есть две большие проблемы:
- Мне приходится использовать X для размера столбца, и поэтому я не могу задать размер своих столбцов (например, если у меня 4 столбца, я хочу, чтобы столбец A составлял 10% размера, а столбцы B, C и D имели оставшуюся часть, распределенную поровну).
- Теперь, когда моя таблица наконец вписывается в ширину страницы, она не учитывает высоту страницы...
Чтобы исправить это, я прочитал документацию и использовал следующий MWE:
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tabularx}
\begin{document}
\begin{table}
{%
\newcommand{\mc}[3]{\multicolumn{#1}{#2}{#3}}
\begin{center}
\begin{tabularx}{\textwidth}{>{\hsize=.25\hsize}X>{\hsize=1.25\hsize}X>{\hsize=1.25\hsize}X>{\hsize=1.25\hsize}X}\cline{2-4}
\textbf{} & \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\\\hline
\mc{1}{|l|}{\textbf{Goal}} & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\\\hline
\mc{1}{|l|}{\textbf{NoSQL and Datastores supported}} & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\\\hline
\mc{1}{|l|}{\textbf{Operations supported}} & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\\\hline
\mc{1}{|l|}{\textbf{No support for}} & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\\\hline
\mc{1}{|l|}{\textbf{Future}} & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\\\hline
\mc{1}{|l|}{\textbf{Commercial support}} & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\\\hline
\mc{1}{|l|}{\textbf{Documentation}} & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\\\hline
\end{tabularx}
\end{center}
}%
\end{table}
\end{document}
Однако, даже если преамбула кажется правильной (для случая с 4 столбцами, где столбцы B, C и D должны быть в 6 раз больше, чем A), ничего не происходит.
Чего именно я хочу? Допустим, общая ширина таблицы составляет 100%. Я бы хотел, чтобы столбец A имел 10% этой ширины, а столбцы B, C и D имели по 30% каждый.
Я также хотел бы, чтобы эта таблица уместилась на одной странице, без расширения на дополнительные страницы. Так что нет, я не могу использовать longtable ...
В настоящее время MWE генерирует что-то вроде этого:
Документацию, с которой я ознакомился, можно найти здесь:
Как мне решить свои проблемы?
решение1
Вот один из способов сделать это:
- Использовать
p{<width>}
для всех столбцов в обычномtabular
. - Для этого создайте новую длину
\tabularlength
и установите ее на общую ширину таблицы. Я использовал.975\linewidth
здесь. - Затем определите каждый из столбцов,
\tabularlength
например , в терминахp{.1\tabularlength}
. - Чтобы заставить первую колонку вести себя хорошо, откажитесь от
multicolumn
того, чтобы линии можно было разорвать. - Это значит, что нам нужны переносы, поэтому загрузите
babel
. - Этого недостаточно, так как это не позволяет переносить первое слово в столбце. Поэтому переносите эти слова вручную, используя
\-
. - Используйте
geometry
для правильной компоновки страницы. - Используйте
>{\bfseries}
для первого столбца, чтобы избежать необходимости указывать жирный шрифт в каждой строке. - Нам по-прежнему нужно одно правило
\multicolumn
для самой первой строки, чтобы не возникало ложных вертикальных правил. - Используйте
\centering
вместо окружения,center
поскольку последнее добавляет дополнительный интервал, который нам здесь не нужен.
Это на самом деле подходит с (немного) запаса места. Если бы таблица была больше, вы могли бы рассмотреть использование \small
в table
среде, чтобы установить размер шрифта немного меньше. Или вы могли бы настроить поля и т. д. с помощью geometry
. Это можно сделать для всего документа или, при необходимости, для одной страницы.
Код
\documentclass[a4paper,10pt,british]{article}
\usepackage{babel,geometry}
\usepackage[utf8]{inputenc}
\usepackage{tabularx}
\begin{document}
\begin{table}
\newlength{\tabularlength}
\setlength{\tabularlength}{.975\linewidth}
\centering
\begin{tabular}{|>{\bfseries}p{.1\tabularlength}|*{3}{p{.3\tabularlength}}}
\cline{2-4}
\multicolumn{1}{l}{} & \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\\\hline
Goal & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\\\hline
NoSQL and Datastores supported & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\\\hline
Oper\-ations supported & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\\\hline
No support for & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\\\hline
Future & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\\\hline
Com\-mer\-cial support & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\\\hline
Docu\-ment\-ation & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\\\hline
\end{tabular}
\end{table}
\end{document}
Выход
Альтернативная раскладка
Я думаю, вы также можете рассмотреть возможность включения табличной части в альбомную ориентацию, так как это может облегчить ее усвоение людьми. Например:
В этом случае я использовал дополнительную директиву форматирования для первого столбца, \raggedright
чтобы он выглядел разумно.
Код для альбомной табличной ориентации
\documentclass[a4paper,10pt,british]{article}
\usepackage{babel,geometry}
\usepackage[utf8]{inputenc}
\usepackage{array}
\usepackage{pdflscape}
\begin{document}
\begin{landscape}
\begin{table}
\newlength{\tabularlength}
\setlength{\tabularlength}{.975\linewidth}
\centering
\begin{tabular}{|>{\bfseries\raggedright}p{.1\tabularlength}|*{3}{p{.3\tabularlength}}}
\cline{2-4}
\multicolumn{1}{l}{} & \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\\\hline
Goal & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\\\hline
NoSQL and Datastores supported & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\\\hline
Oper\-ations supported & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\\\hline
No support for & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\\\hline
Future & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\\\hline
Com\-mer\-cial support & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\\\hline
Docu\-ment\-ation & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\\\hline
\end{tabular}
\end{table}
\end{landscape}
\end{document}
Центрированные столбцы и вертикальные линии
Как отметил Flame_Phoenix в комментариях, m{<width>}
дает столбец указанной ширины, который центрирован по вертикали. Этот спецификатор требует пакет array
.
Добавление вертикальной линии перед «Hibernate OGM» — это всего лишь вопрос настройки \multicolumn
для первой записи таблицы. Центрирование всех ячеек по горизонтали, а также по вертикали можно выполнить, добавив >{\centering}
табличную конфигурацию. Однако это становится немного утомительным и сложнее для последовательной настройки. Лучшее решение использует возможность array
определения нового типа столбца.
\newcolumntype{M}{>{\centering}m{.3\tabularlength}}
Поскольку в моем примере показана компоновка как для портретной, так и для альбомной ориентации, мне также нужно вытащить добавление \tabularlength
из tabular
окружения, чтобы не пытаться определить уже определенную длину.
\newlength{\tabularlength}
Тип m
столбца воспринимается \\
как новая строка внутри столбца, а не как конец строки. Поэтому мне нужно заменить \\\hline
на \tabularnewline\hline
.
Наконец, для аккуратности я добавил вертикальную линейку справа.
Код
\documentclass[a4paper,10pt,british]{article}
\usepackage{babel,geometry}
\usepackage[utf8]{inputenc}
\usepackage{array}
\usepackage{pdflscape}
\newlength{\tabularlength}
\newcolumntype{M}{>{\centering}m{.3\tabularlength}}
\begin{document}
\begin{table}
\setlength{\tabularlength}{.975\linewidth}
\centering
\begin{tabular}{|>{\centering\bfseries}m{.1\tabularlength}|*{3}{M}|}
\cline{2-4}
\multicolumn{1}{l|}{} & \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\tabularnewline\hline
Goal & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\tabularnewline\hline
NoSQL and Datastores supported & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\tabularnewline\hline
Oper\-ations supported & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\tabularnewline\hline
No support for & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\tabularnewline\hline
Future & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\tabularnewline\hline
Com\-mer\-cial support & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\tabularnewline\hline
Docu\-ment\-ation & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\tabularnewline\hline
\end{tabular}
\end{table}
\begin{landscape}
\begin{table}
\setlength{\tabularlength}{.975\linewidth}
\centering
\begin{tabular}{|>{\bfseries\centering}m{.1\tabularlength}|*{3}{M}|}
\cline{2-4}
\multicolumn{1}{l|}{} & \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\tabularnewline\hline
Goal & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\tabularnewline\hline
NoSQL and Datastores supported & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\tabularnewline\hline
Operations supported & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\tabularnewline\hline
No support for & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\tabularnewline\hline
Future & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\tabularnewline\hline
Commercial support & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\tabularnewline\hline
Document\-ation & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\tabularnewline\hline
\end{tabular}
\end{table}
\end{landscape}
\end{document}
Выход
решение2
Ваша главная ошибка заключалась в многостолбцовости, которая заменяла столбец указанной ширины столбцом естественной ширины l
.
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{array}
\begin{document}
\begin{table}
\centering\small
\newcommand{\mc}[3]{\multicolumn{#1}{#2}{#3}}
\setlength{\dimen0}{\dimexpr\textwidth-6\tabcolsep\relax}
\begin{tabular}{@{}>{\hspace*{0pt}\bfseries}p{.1\dimen0}*3{p{.3\dimen0}}}
& \textbf{Hibernate OGM} & \textbf{EclipseLink NoSQL} & \textbf{DataNucleus}\\\hline
Goal & Complement JPA with NoSQL, key-value stores & Integrates in the father project main goal of providing a complete persistence solution & Being a standards compliant and efficient JPA and JDO platform\\\hline
NoSQL and Datastores supported & Infinispan, EHCache, MongoDB & MongoDB, Oracle NoSQL, Oracle AQ, JMS, XML files & Google Big Table, MongoDB, Cassandra, Excel, OOXML, ODF, XML, HBase, AppEngine/DataStore, Neo4j, JSON, Amazon S3, GoogleStorage, LDAP, NeoDatis, db4o\\\hline
Operations supported & Object Oriented queries (JP-QL), CRUD of entities, Polymorphic entities, Embeddable objects, Basic types (partial), Unidirectional and Bidirectional relationships (partial), Collections, Hibernate Search queries, JPA and Hibernate ORM API & Object Oriented Queries, Polymorphic entities, Basic types, Unidirectional relationships, Collections, JPA (partial), Complex hierarchical, Indexed hierarchical data, Mapped hierarchical data, CRUD operations, Embedded objects and collections, Inheritance, Subset of JP-QL and Criteria API, Denormalization & CRUD operations, Embedded objects and collections, Inheritance, Relationships (Unidirectional and Bidirectional), Queries for JP-QL, JDOQL and SQL (partial), Basic types, Joins.\\\hline
No support for & Denormalization, Complex joins and aggregations & Joins & Aggregations? (not specified in documentation)\\\hline
Future & High performance sequence generator, parallel key fetching, support for Map/Reduce, more NoSQL classes, better mixing of NoSQL and RDBMS & ? & JPA2.1 full feature list, Official support for Cassandra, Considering a plugin for REDIS\\\hline
Commercial support & Red Hat & Oracle (via TopLink) & Supported by DataNucleus team\\\hline
Documentation & Scattered, inactive forums, official documentation lacking & Bureaucratic forums, information is complete and gathered mainly in the official website & Active forums, acceptable official documentation, but the big advantage comes from user support in form of blogs and posts scattered around the Internet\\\hline
\end{tabular}
\end{table}
\end{document}