Код

Код

Я использую 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}

Связанный контент