LaTex 排版 （2）：表格
LaTeX
![](/data/attachment/album/202102/23/113655fm74zku5x1xy7h5j.png)


LaTeX 提供了许多工具来创建和定制表格，在本系列中，我们将使用 `tabular` 和 `tabularx` 环境来创建和定制表。


### 基础表格


要创建表，只需指定环境 `\begin{tabular}{列选项}`：



```
\begin{tabular}{c|c}
    Release &Codename \\ \hline
    Fedora Core 1 &Yarrow \\ 
    Fedora Core 2 &Tettnang \\ 
    Fedora Core 3 &Heidelberg \\ 
    Fedora Core 4 &Stentz \\ 
\end{tabular}

```

![Basic Table](/data/attachment/album/202102/23/113656b56vdxd4x15evw69.png)


在上面的示例中，花括号中的 ”{c|c}” 表示文本在列中的位置。下表总结了位置参数及其说明。




| 参数 | 位置 |
| --- | --- |
| `c` | 将文本置于中间 |
| `l` | 将文本左对齐 |
| `r` | 将文本右对齐 |
| `p{宽度}` | 文本对齐单元格顶部 |
| `m{宽度}` | 文本对齐单元格中间 |
| `b{宽度}` | 文本对齐单元格底部 |



> 
> `m{宽度}` 和 `b{宽度}` 都要求在最前面指定数组包。
> 
> 
> 


使用上面的例子，让我们来详细讲解使用的要点，并描述你将在本系列中看到的更多选项：




| 选项 | 意义 |
| --- | --- |
| `&` | 定义每个单元格，这个符号仅用于第二列 |
| `\\` | 这将终止该行并开始一个新行 |
| `|` | 指定表格中的垂直线（可选） |
| `\hline` | 指定表格中的水平线（可选） |
| `*{数量}{格式}` | 当你有许多列时，可以使用这个，并且是限制重复的有效方法 |
| `||` | 指定表格中垂直双线 |


### 定制表格


学会了这些选项，让我们使用这些选项创建一个表。



```
\begin{tabular}{*{3}{|l|}}
\hline
	\textbf{Version} &\textbf{Code name} &\textbf{Year released} \\
\hline
	Fedora 6 &Zod &2006 \\ \hline
	Fedora 7 &Moonshine &2007 \\ \hline
	Fedora 8 &Werewolf &2007 \\
\hline
\end{tabular}

```

![Customise Table](/data/attachment/album/202102/23/113656kvzgzbqi0l1jiiez.png)


### 管理长文本


如果列中有很多文本，那么它的格式就不好处理，看起来也不好看。


下面的示例显示了文本的格式长度，我们将在导言区中使用 `blindtext`，以便生成示例文本。



```
\begin{tabular}{|l|l|}\hline
	Summary &Description \\ \hline
	Test &\blindtext \\
\end{tabular}

```

![Default Formatting](/data/attachment/album/202102/23/113656qt28t2a9zz9ydn5a.png)


正如你所看到的，文本超出了页面宽度；但是，有几个选项可以克服这个问题。


* 指定列宽，例如 `m{5cm}`
* 利用 `tablarx` 环境，这需要在导言区中引用 `tablarx` 宏包。


#### 使用列宽管理长文本


通过指定列宽，文本将被折行为如下示例所示的宽度。



```
\begin{tabular}{|l|m{14cm}|} \hline
	Summary &Description \\ \hline
	Test &\blindtext \\ \hline
\end{tabular}\vspace{3mm}

```

![Column Width](/data/attachment/album/202102/23/113657wvz00wc2kcxdqvtv.png)


#### 使用 tabularx 管理长文本


在我们利用表格之前，我们需要在导言区中加上它。`tabularx` 方法见以下示例：`\begin{tabularx}{宽度}{列选项}`。



```
\begin{tabularx}{\textwidth}{|l|X|} \hline
Summary & Tabularx Description\\ \hline
Text &\blindtext \\ \hline
\end{tabularx}

```

![Tabularx](/data/attachment/album/202102/23/113657mvm6uhe7vmhcem34.png)


请注意，我们需要处理长文本的列在花括号中指定了大写 `X`。


### 合并行合并列


有时需要合并行或列。本节描述了如何完成。要使用 `multirow` 和 `multicolumn`，请将 `multirow` 添加到导言区。


#### 合并行


`multirow` 采用以下参数 `\multirow{行的数量}{宽度}{文本}`，让我们看看下面的示例。



```
\begin{tabular}{|l|l|}\hline
	Release &Codename \\ \hline
	Fedora Core 4 &Stentz \\ \hline
	\multirow{2}{*}{MultiRow} &Fedora 8 \\ 
	&Werewolf \\ \hline
\end{tabular}

```

![MultiRow](/data/attachment/album/202102/23/113657jd1y1mbzcd1sbyh1.png)


在上面的示例中，指定了两行，`*` 告诉 LaTeX 自动管理单元格的大小。


#### 合并列


`multicolumn` 参数是 `{multicolumn{列的数量}{单元格选项}{位置}{文本}`，下面的示例演示合并列。



```
\begin{tabular}{|l|l|l|}\hline
	Release &Codename &Date \\ \hline
	Fedora Core 4 &Stentz &2005 \\ \hline
	\multicolumn{3}{|c|}{Mulit-Column} \\ \hline
\end{tabular}

```

![Multi-Column](/data/attachment/album/202102/23/113658hn9dvnqd20psdvpn.png)


### 使用颜色


可以为文本、单个单元格或整行指定颜色。此外，我们可以为每一行配置交替的颜色。


在给表添加颜色之前，我们需要在导言区引用 `\usepackage[table]{xcolor}`。我们还可以使用以下颜色参考 [LaTeX Color](https://latexcolor.com) 或在颜色前缀后面添加感叹号（从 0 到 100 的阴影）来定义颜色。例如，`gray！30`。



```
\definecolor{darkblue}{rgb}{0.0, 0.0, 0.55}
\definecolor{darkgray}{rgb}{0.66, 0.66, 0.66}

```

下面的示例演示了一个具有各种颜色的表，`\rowcolors` 采用以下选项 `\rowcolors{起始行颜色}{偶数行颜色}{奇数行颜色}`。



```
\rowcolors{2}{darkgray}{gray!20}
\begin{tabular}{c|c}
	Release &Codename \\ \hline
	Fedora  Core 1 &Yarrow \\
	Fedora Core 2 &Tettnang \\
	Fedora Core 3 &Heidelberg \\
	Fedora Core 4 &Stentz \\
\end{tabular}

```

![Alt colour table](/data/attachment/album/202102/23/113658uqg4sszyglqwiklw.png)


除了上面的例子，`\rowcolor` 可以用来指定每一行的颜色，这个方法在有合并行时效果最好。以下示例显示将 `\rowColors` 与合并行一起使用的影响以及如何解决此问题。


![Impact on multi-row](/data/attachment/album/202102/23/113658cupkwcukb81odh8b.png)


你可以看到，在合并行中，只有第一行能显示颜色。想要解决这个问题，需要这样做：



```
\begin{tabular}{|l|l|}\hline
	\rowcolor{darkblue}\textsc{\color{white}Release}  &\textsc{\color{white}Codename} \\ \hline
	\rowcolor{gray!10}Fedora Core 4 &Stentz \\ \hline
	\rowcolor{gray!40}&Fedora 8 \\ 
	\rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &Werewolf \\ \hline
\end{tabular}

```

![Multi-row](/data/attachment/album/202102/23/113658ixxh6wppghlxzlia.png)


让我们讲解一下为解决合并行替换颜色问题而实施的更改。


* 第一行从合并行上方开始
* 行数从 `2` 更改为 `-2`，这意味着从上面的行开始读取
* `\rowcolor` 是为每一行指定的，更重要的是，多行必须具有相同的颜色，这样才能获得所需的结果。


关于颜色的最后一个注意事项是，要更改列的颜色，需要创建新的列类型并定义颜色。下面的示例说明了如何定义新的列颜色。



```
\newcolumntype{g}{>{\columncolor{darkblue}}l} 

```

我们把它分解一下：


* `\newcolumntype{g}`：将字母 `g` 定义为新列
* `{>{\columncolor{darkblue}}l}`：在这里我们选择我们想要的颜色，并且 `l` 告诉列左对齐，这可以用 `c` 或 `r` 代替。



```
\begin{tabular}{g|l} 
	\textsc{Release}  &\textsc{Codename} \\ \hline
	Fedora Core 4 &Stentz \\ 
	&Fedora 8 \\ 
	\multirow{-2}{*}{Multi-Row} &Werewolf \\ 
\end{tabular}\

```

![Column Colour](/data/attachment/album/202102/23/113659kz79ixig6s6a6gei.png)


### 横向表


有时，你的表可能有许多列，纵向排列会很不好看。在导言区加入 `rotating` 包，你将能够创建一个横向表。下面的例子说明了这一点。


对于横向表，我们将使用 `sidewaystable` 环境并在其中添加表格环境，我们还指定了其他选项。


* `\centering` 可以将表格放置在页面中心
* `\caption{}` 为表命名
* `\label{}` 这使我们能够引用文档中的表



```
\begin{sidewaystable}
\centering
\caption{Sideways Table}
\label{sidetable}
\begin{tabular}{ll}
	\rowcolor{darkblue}\textsc{\color{white}Release}  &\textsc{\color{white}Codename} \\ 
	\rowcolor{gray!10}Fedora Core 4 &Stentz \\ 
	\rowcolor{gray!40} &Fedora 8 \\ 
	\rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &Werewolf \\ 
\end{tabular}\vspace{3mm}
\end{sidewaystable}

```

![Sideways Table](/data/attachment/album/202102/23/113659kk7nt07l6gmy6lj2.png)


### 列表和表格


要将列表包含到表中，可以使用 `tabularx`，并将列表包含在指定的列中。另一个办法是使用表格格式，但必须指定列宽。


#### 用 tabularx 处理列表



```
\begin{tabularx}{\textwidth}{|l|X|} \hline
	Fedora Version &Editions \\ \hline
	Fedora 32 &\begin{itemize}[noitemsep]
		\item CoreOS
		\item Silverblue
		\item IoT
	\end{itemize} \\ \hline
\end{tabularx}\vspace{3mm}

```

![List in tabularx](/data/attachment/album/202102/23/113700myi4lvtptpnknzy8.png)


#### 用 tabular 处理列表



```
\begin{tabular}{|l|m{6cm}|}\hline
        Fedora Version &amp;amp;amp;Editions \\\ \hline
    Fedora 32 &amp;amp;amp;\begin{itemize}[noitemsep]
        \item CoreOS
        \item Silverblue
        \item IoT
    \end{itemize} \\\ \hline
\end{tabular}

```

![List in tabular](/data/attachment/album/202102/23/113700ixz7vtxxtv933r3r.png)


### 总结


LaTeX 提供了许多使用 `tablar` 和 `tablarx` 自定义表的方法，你还可以在表环境 （`\begin\table`） 中添加 `tablar` 和 `tablarx` 来添加表的名称和定位表。


### LaTeX 宏包


所需的宏包有如下这些：



```
\usepackage{fullpage}
\usepackage{blindtext}  % add demo text
\usepackage{array} % used for column positions
\usepackage{tabularx} % adds tabularx which is used for text wrapping
\usepackage{multirow} % multi-row and multi-colour support
\usepackage[table]{xcolor} % add colour to the columns 
\usepackage{rotating} % for landscape/sideways tables

```

### 额外的知识


这是一堂关于表的小课，有关表和 LaTex 的更多高级信息，请访问 [LaTex Wiki](https://en.wikibooks.org/wiki/LaTeX/Tables)


![](/data/attachment/album/202102/23/113659kz79ixig6s6a6gei.png)




---


via: <https://fedoramagazine.org/latex-typesetting-part-2-tables/>


作者：[Earl Ramirez](https://fedoramagazine.org/author/earlramirez/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[Chao-zhi](https://github.com/Chao-zhi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
LaTeX offers a number of tools to create and customise tables, in this series we will be using the tabular and tabularx environment to create and customise tables.

## Basic table

To create a table you simply specify the environment \begin{tabular}{columns}

\begin{tabular}{c|c} Release &Codename \\ \hline Fedora Core 1 &Yarrow \\ Fedora Core 2 &Tettnang \\ Fedora Core 3 &Heidelberg \\ Fedora Core 4 &Stentz \\ \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-13.png)

In the above example “{c|c}” in the curly bracket refers to the position of the text in the column. The below table summarises the positional argument together with the description.

Position | Argument |
---|---|

c | Position text in the centre |

l | Position text left-justified |

r | Position text right-justified |

p{width} | Align the text at the top of the cell |

m{width} | Align the text in the middle of the cell |

b{width} | Align the text at the bottom of the cell |


Both m{width} and b{width} requires the array package to be specified in the preamble.

Using the example above, let us breakdown the important points used and describe a few more options that you will see in this series

Option | Description |
---|---|

& | Defines each cell, the ampersand is only used from the second column |

\\ | This terminates the row and start a new row |

| | Specifies the vertical line in the table (optional) |

\hline | Specifies the horizontal line (optional) |

*{num}{form} | This is handy when you have many columns and is an efficient way of limiting the repetition |

|| | Specifies the double vertical line |


## Customizing a table

Now that some of the options available are known, let us create a table using the options described in the previous section.

\begin{tabular}{*{3}{|l|}} \hline \textbf{Version} &\textbf{Code name} &\textbf{Year released} \\ \hline Fedora 6 &Zod &2006 \\ \hline Fedora 7 &Moonshine &2007 \\ \hline Fedora 8 &Werewolf &2007 \\ \hline \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-23.png)

## Managing long text

With LaTeX, if there are many texts in a column it will not be formatted well and does not look presentable.

The below example shows how long text is formatted, we will use “blindtext” in the preamble so that we can produce sample text.

\begin{tabular}{|l|l|}\hline Summary &Description \\ \hline Test &\blindtext \\ \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-10.png)

As you can see the text exceeds the page width; however, there are a couple of options to overcome this challenge.

- Specify the column width, for example, m{5cm}
- Utilise the tabularx environment, this requires tabularx package in the preamble.

### Managing long text with column width

By specifying the column width the text will be wrapped into the width as shown in the example below.

\begin{tabular}{|l|m{14cm}|} \hline Summary &Description \\ \hline Test &\blindtext \\ \hline \end{tabular}\vspace{3mm}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-11.png)

### Managing long text with tabularx

Before we can leverage tabularx we need to add it in the preamble. Tabularx takes the following example

**\begin{tabularx}{width}{columns}** \begin{tabularx}{\textwidth}{|l|X|} \hline Summary & Tabularx Description\\ \hline Text &\blindtext \\ \hline \end{tabularx}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-12.png)

Notice that the column that we want the long text to be wrapped has a capital “X” specified.

## Multi-row and multi-column

There are times when you will need to merge rows and/or column. This section describes how it is accomplished. To use multi-row and multi-column add multi-row to the preamble.

### Multirow

Multirow takes the following argument *\multirow{number_of_rows}{width}{text}*, let us look at the below example.

\begin{tabular}{|l|l|}\hline Release &Codename \\ \hline Fedora Core 4 &Stentz \\ \hline \multirow{2}{*}{MultiRow} &Fedora 8 \\ &Werewolf \\ \hline \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-15.png)

In the above example, two rows were specified, the ‘*’ tells LaTeX to automatically manage the size of the cell.

### Multicolumn

Multicolumn argument is *\multicolumn{number_of_columns}{cell_position}{text}*, below example demonstrates multicolumn.

\begin{tabular}{|l|l|l|}\hline Release &Codename &Date \\ \hline Fedora Core 4 &Stentz &2005 \\ \hline \multicolumn{3}{|c|}{Mulit-Column} \\ \hline \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-16.png)

## Working with colours

Colours can be assigned to the text, an individual cell or the entire row. Additionally, we can configure alternating colours for each row.

Before we can add colour to our tables we need to include *\usepackage[table]{xcolor}* into the preamble. We can also define colours using the following colour reference [LaTeX Colour](https://latexcolor.com) or by adding an exclamation after the colour prefixed by the shade from 0 to 100. For example, *gray!30*

\definecolor{darkblue}{rgb}{0.0, 0.0, 0.55} \definecolor{darkgray}{rgb}{0.66, 0.66, 0.66}

Below example demonstrate this a table with alternate colours, \rowcolors take the following options *\rowcolors{row_start_colour}{even_row_colour}{odd_row_colour}*.

\rowcolors{2}{darkgray}{gray!20} \begin{tabular}{c|c} Release &Codename \\ \hline Fedora Core 1 &Yarrow \\ Fedora Core 2 &Tettnang \\ Fedora Core 3 &Heidelberg \\ Fedora Core 4 &Stentz \\ \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-17.png)

In addition to the above example, \rowcolor can be used to specify the colour of each row, this method works best when there are multi-rows. The following examples show the impact of using the \rowcolours with multi-row and how to work around it.

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-18.png)

As you can see the *multi-row* is visible in the first row, to fix this we have to do the following.

\begin{tabular}{|l|l|}\hline \rowcolor{darkblue}\textsc{\color{white}Release} &\textsc{\color{white}Codename} \\ \hline \rowcolor{gray!10}Fedora Core 4 &Stentz \\ \hline \rowcolor{gray!40}&Fedora 8 \\ \rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &Werewolf \\ \hline \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-19.png)

Let us discuss the changes that were implemented to resolve the multi-row with the alternate colour issue.

- The first row started above the multi-row
- The number of rows was changed from 2 to -2, which means to read from the line above
- \rowcolor was specified for each row, more importantly, the multi-rows must have the same colour so that you can have the desired results.

One last note on colour, to change the colour of a column you need to create a new column type and define the colour. The example below illustrates how to define the new column colour.

\newcolumntype{g}{>{\columncolor{darkblue}}l}

Let’s break it down:

- \newcolumntype{g}: defines the letter
*g*as the new column - {>{\columncolor{darkblue}}l}: here we select our desired colour, and
*l*tells the column to be left-justified, this can be subsitued with*c*or*r*

\begin{tabular}{g|l} \textsc{Release} &\textsc{Codename} \\ \hline Fedora Core 4 &Stentz \\ &Fedora 8 \\ \multirow{-2}{*}{Multi-Row} &Werewolf \\ \end{tabular}\

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-24.png)

## Landscape table

There may be times when your table has many columns and will not fit elegantly in portrait. With the *rotating* package in preamble you will be able to create a sideways table. The below example demonstrates this.

For the landscape table, we will use the *sidewaystable* environment and add the tabular environment within it, we also specified additional options.

- \centering to position the table in the centre of the page
- \caption{} to give our table a name
- \label{} this enables us to reference the table in our document

\begin{sidewaystable} \centering \caption{Sideways Table} \label{sidetable} \begin{tabular}{ll} \rowcolor{darkblue}\textsc{\color{white}Release} &\textsc{\color{white}Codename} \\ \rowcolor{gray!10}Fedora Core 4 &Stentz \\ \rowcolor{gray!40} &Fedora 8 \\ \rowcolor{gray!40}\multirow{-2}{*}{Multi-Row} &Werewolf \\ \end{tabular}\vspace{3mm} \end{sidewaystable}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-20.png)

## Lists in tables

To include a list into a table you can use tabularx and include the list in the column where the *X* is specified. Another option will be to use tabular but you must specify the column width.

### List in tabularx

\begin{tabularx}{\textwidth}{|l|X|} \hline Fedora Version &Editions \\ \hline Fedora 32 &\begin{itemize}[noitemsep] \item CoreOS \item Silverblue \item IoT \end{itemize} \\ \hline \end{tabularx}\vspace{3mm}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-21.png)

### List in tabular

\begin{tabular}{|l|m{6cm}|}\hline Fedora Version &Editions \\ \hline Fedora 32 &\begin{itemize}[noitemsep] \item CoreOS \item Silverblue \item IoT \end{itemize} \\ \hline \end{tabular}

![](https://fedoramagazine.org/wp-content/uploads/2020/06/image-22.png)

## Conclusion

LaTeX offers many ways to customise your table with tabular and tabularx, you can also add both tabular and tabularx within the table environment (\begin\table) to add the table name and to position the table.

The packages used in this series are:

\usepackage{fullpage} \usepackage{blindtext} % add demo text \usepackage{array} % used for column positions \usepackage{tabularx} % adds tabularx which is used for text wrapping \usepackage{multirow} % multi-row and multi-colour support \usepackage[table]{xcolor} % add colour to the columns \usepackage{rotating} % for landscape/sideways tables

## Additional Reading

This was an intermediate lesson on tables. For more advanced information about tables and LaTex in general, you can go to the [LaTeX Wiki](https://en.wikibooks.org/wiki/LaTeX/Tables).

## bgd

In addition to the rotating package, the package pdflscape will allow one to create a table (or other text) that is rotated, which in addition will be oriented correctly when viewed online by using \begin{landscape} and \end{landscape}.

## Earl Ramirez

Thanks, bgd

## nated

The part about resizing tables was really helpful. I’ve struggled with that in the past.

## rthrt

nice

please write some about lilipond

## Earl Ramirez

Are you referring to the LiliPond for music?

## Göran Uddeborg

Thanks! I’ve used LaTeX for many years (if somewhat sporadically) but there is always something more to learn. You taught me some new nice things.

A little mistake to correct: in the list of “options”, to be used in tables in the beginning you say that a single backslash starts a new line. That should be a double backslash, I believe.

## Earl Ramirez

Glad that it was helpful for you, good catch, yes, it’s a double backslash that starts a new row. Must have missed the escape character.

Thanks.

## Kenedy

You’re right, is a double backslash.

## ydor9e

Talking about tables, an interesting subject is how to brake a table when it does not fit in a single page. I always struggle to do that.

## Earl Ramirez

The longtable package (https://www.ctan.org/pkg/longtable) will resolve this for you, here is an example that you can use.

\documentclass[a4paper,11pt]{article}

\usepackage{blindtext}

\usepackage{longtable}

\usepackage{array}

\usepackage{multirow}

\usepackage{fullpage}

%opening

\title{}

\author{}

\begin{document}

\maketitle

\section{Long Table}

\begin{longtable}{|l|p{14cm}|}

\caption{Multi-page Table} \

\hline

\multicolumn{2}{|c|}{Begin Table} \

\hline

Name &Description \

\endfirsthead % Specify the header, this will be shown on each page

\multicolumn{2}{|c|}{Table Continues} \\ \hline

{\bfseries Name} &{\bfseries Description} \\

\endhead % Tells ``Table Continues'' to show above the header

\hline

\endfoot

\hline

\multicolumn{2}{|c|}{End of Table} \\

\hline

\endlastfoot %

Text1 &\blindtext \\

Text2 &\blindtext \\

Text3 &\blindtext\\

Text4 &\blindtext \\

Text5 &\blindtext \\

Text6 &\blindtext \\

Text7 &\blindtext \\

Text8 &\blindtext \\

Text9 &\blindtext \\

Text10 &\blindtext \\

\end{longtable}

\end{document}

## galeon

Please consider writting part 3 about for loop’s (ex forloop package) which can be used to automatic genereation of tables. I use them once to insert many (more than 20) similar figures.

## Earl Ramirez

I will try and squeeze it in to one of the future articles, thanks.