38 KiB
Tables
!> Paragraphs requires an understanding of Sections.
Intro
Tablescontain a list ofRowsRowscontain a list ofTableCellsTableCellscontain a list ofParagraphsand/orTables. You can addTablesas tables can be nested inside each other
Create a simple table, then add the table in the section:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Name")] }), new TableCell({ children: [new Paragraph("Age")] })],
}),
new TableRow({
children: [new TableCell({ children: [new Paragraph("Alice")] }), new TableCell({ children: [new Paragraph("32")] })],
}),
new TableRow({
children: [new TableCell({ children: [new Paragraph("Bob")] }), new TableCell({ children: [new Paragraph("27")] })],
}),
],
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Table
Set Width
const table = new Table({
...,
width: {
size: [TABLE_WIDTH],
type: WidthType,
}
});
For example:
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
}),
],
width: {
size: 4535,
type: WidthType.DXA,
},
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Column Widths
A table's columns are defined by its grid (w:tblGrid), whose widths are always in twips (twentieths of a point). You can set them explicitly with columnWidths:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("3505 twips wide")] }),
new TableCell({ children: [new Paragraph("5505 twips wide")] }),
],
}),
],
columnWidths: [3505, 5505],
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Word lays a table out from its cells' widths, and sizes the columns of cells without one to their text, whatever the grid says. So docx gives each cell without a width of its own the width of the columns it spans, and Word keeps the widths you asked for. When the table's width is wider than its columns add up to, the cells' widths are scaled up to fill it, as Word and LibreOffice lay the columns out, so columnWidths: [20, 80] in a table 100% wide gives columns of 20% and 80% there. The grid is written as given, though, and readers that go by the grid alone take those as 20 and 80 twips. Without a width, a table is as wide as its columns.
When columnWidths is omitted, docx derives the grid for you from the table's width and the cells' widths. Percentages are resolved against the actual page size and margins of the section the table is in (or the parent cell for nested tables) when the document is packed, and columns without a width share whatever is left equally. So a 100% wide table with 90% / 10% cells on a default A4 page gets a grid of [8123, 903], and a table with no widths at all gets equal, full-width columns.
!> Microsoft Word lays tables out from the widths and only treats the grid as a hint, but Google Docs, Apple Pages, QuickLook and many other readers lay tables out from the grid alone and ignore percentage widths. Earlier versions of docx wrote a placeholder grid of 100 twips per column, which made every table with percentage widths collapse to one character per column in those readers. If you set columnWidths yourself, make sure the values are real twips that match your intended widths.
Cell Margins
Cells have the margins Word gives the tables it makes: 0.075 inches (108 twips) on the left and right, and none above or below. They come from Normal Table, the default table style docx writes. Without it, Word gives cells no margins, and their text touches the borders. Set margins on a table, or on a cell, to give them others. Styles from externalStyles with a Normal Table of their own use theirs.
Set Indent
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
}),
],
indent: {
size: 600,
type: WidthType.DXA,
},
});
const doc = new Document({
sections: [
{
children: [new Paragraph("This paragraph starts at the margin, and the table below is indented from it."), table],
},
],
});
Alignment
A table starts at the left margin. Set alignment to center it in the column, or put it against the right margin. It stays in line with the text, with the paragraphs before it above it and the paragraphs after it below it.
import { AlignmentType, Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
}),
],
width: {
size: 4000,
type: WidthType.DXA,
},
alignment: AlignmentType.CENTER,
});
const doc = new Document({
sections: [
{
children: [
new Paragraph("The table below is centered between the margins."),
table,
new Paragraph("This paragraph is below it."),
],
},
],
});
Borders and table styles
A table without a style has thin single borders, unless borders gives it others. Each side that borders leaves out stays a thin single line.
A table with a style takes its borders from the style. Only the sides that borders gives are written, so they replace the style's borders on those sides, and the style keeps the rest. To take away a style's border on one side, give that side BorderStyle.NONE.
import { BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
import * as fs from "fs";
const table = new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
}),
new TableRow({
children: [new TableCell({ children: [new Paragraph("Foo")] }), new TableCell({ children: [new Paragraph("Bar")] })],
}),
],
// A table style with red dashed borders, from demo/assets/custom-styles.xml
style: "MyCustomTableStyle",
// Replaces the style's top border, and keeps its other borders
borders: {
top: { style: BorderStyle.DOUBLE, size: 12, color: "0000FF" },
},
});
const doc = new Document({
externalStyles: fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8"),
sections: [
{
children: [table],
},
],
});
Table Row
A table consists of multiple table rows. Table rows have a list of children which accepts a list of table cells explained below. You can create a simple table row like so:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const tableRow = new TableRow({
children: [
new TableCell({
children: [new Paragraph("hello")],
}),
],
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [tableRow] })],
},
],
});
Or preferably, add the tableRow directly into the table without declaring a variable:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("hello")],
}),
],
}),
],
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Options
Here is a list of options you can add to the table row:
| Property | Type | Notes |
|---|---|---|
| children | Array<TableCell> |
Required |
| cantSplit | boolean |
Optional |
| keepNext | boolean |
Optional |
| tableHeader | boolean |
Optional |
| height | { value: number, rule: HeightRule } |
Optional |
A row with no cells isn't written, because Word can't open a document with one. A table whose rows all have no cells is written with no rows, which Word shows nothing for. To keep an empty row, such as a row of space with a height, give it an empty cell: new TableCell({ children: [] }).
Repeat row
If a table is paginated on multiple pages, it is possible to repeat a row at the top of each new page by setting tableHeader to true:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const row = new TableRow({
children: [new TableCell({ children: [new Paragraph("Item")] }), new TableCell({ children: [new Paragraph("Quantity")] })],
tableHeader: true,
});
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
row,
// Enough rows to run onto a second page, where the header row repeats
...Array.from(
{ length: 60 },
(_, index) =>
new TableRow({
children: [
new TableCell({ children: [new Paragraph(`Item ${index + 1}`)] }),
new TableCell({ children: [new Paragraph(`${index + 1}`)] }),
],
}),
),
],
}),
],
},
],
});
Only rows at the top of a table repeat. Word repeats the table's first row, and the rows straight after it that also set tableHeader, and ignores tableHeader on any row further down. So a table has one set of header rows, and a row with tableHeader in the middle of it neither repeats nor stops the header rows above it from repeating.
To give each part of a long table a header of its own, make each part a table, with its header row first. Word joins tables that are next to each other into one, so put a paragraph between them, such as a heading for the part:
import { Document, HeadingLevel, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = (text: string) => new TableCell({ children: [new Paragraph(text)] });
const part = (name: string) => [
new Paragraph({ text: name, heading: HeadingLevel.HEADING_2 }),
new Table({
rows: [
// The first row of each table repeats on each page that table runs onto
new TableRow({ children: [cell(`${name} item`), cell("Quantity")], tableHeader: true }),
...Array.from({ length: 40 }, (_, index) => new TableRow({ children: [cell(`${name} ${index + 1}`), cell(`${index + 1}`)] })),
],
}),
];
const doc = new Document({
sections: [
{
children: [...part("Fruit"), ...part("Vegetable"), ...part("Grain")],
},
],
});
Pagination
Prevent row pagination
To prevent breaking contents of a row across multiple pages, call cantSplit:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const row = new TableRow({
children: [
new TableCell({
children: [
new Paragraph("The lines of this row stay together."),
new Paragraph("If the row doesn't fit at the bottom of a page,"),
new Paragraph("the whole row moves to the next page."),
],
}),
],
cantSplit: true,
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [row] })],
},
],
});
Rows taller than a page
Word never splits a row whose height has rule: HeightRule.EXACT, as the row is exactly that tall. When such a row is taller than the space left on a page, Word moves it to the top of the next page, and whatever doesn't fit there runs over the footer and off the bottom of the page, where it's cut off.
For a row that's at least a certain height but grows with what's in it, use HeightRule.ATLEAST. It splits across pages like any other row:
import { Document, HeightRule, Paragraph, Table, TableCell, TableRow } from "docx";
const row = new TableRow({
// At least 2 inches (2880 twips) tall, and taller when its lines need more room
height: { value: 2880, rule: HeightRule.ATLEAST },
children: [
new TableCell({
children: Array.from({ length: 70 }, (_, index) => new Paragraph(`Line ${index + 1}`)),
}),
],
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [row] })],
},
],
});
Keep a table on one page
Word has no setting that keeps a whole table on one page. Instead, set keepNext on every row except the last, so each row stays on the same page as the row after it, and cantSplit on every row. A row's keepNext keeps each paragraph in its cells with the next, unless the paragraph sets keepNext itself. If the last row has keepNext too, the table is also kept with whatever follows it. A table taller than a page still splits.
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const fruit = ["Apples", "Pears", "Figs", "Plums"];
const table = new Table({
rows: fruit.map(
(name, index) =>
new TableRow({
cantSplit: true,
// Every row but the last is kept with the next row
keepNext: index < fruit.length - 1,
children: [new TableCell({ children: [new Paragraph(name)] })],
}),
),
});
const doc = new Document({
sections: [
{
children: [new Paragraph("If the table doesn't fit at the bottom of a page, all of it moves to the next page."), table],
},
],
});
Keep rows merged together on one page
A cell merged down several rows (rowSpan) is written as a cell in each of them, and docx adds the cells below the first, so they have no paragraphs of yours to set keepNext on. Word keeps a row with the next when its first cell's paragraphs are, so with the merged cell in the first column, use the row's keepNext, which sets it on those cells too. Set it on every row of a group but the last, and each group stays on one page while the table can still break between groups.
import { Document, Paragraph, Table, TableCell, TableRow, VerticalAlignTable } from "docx";
const groups = [
{ name: "Fruit", items: ["Apples", "Pears", "Figs"] },
{ name: "Vegetables", items: ["Leeks", "Carrots", "Peas", "Beans"] },
];
const table = new Table({
rows: groups.flatMap(({ name, items }) =>
items.map(
(item, index) =>
new TableRow({
cantSplit: true,
// Keep each row with the next, but for the group's last
keepNext: index < items.length - 1,
children: [
...(index === 0
? [
new TableCell({
rowSpan: items.length,
verticalAlign: VerticalAlignTable.CENTER,
children: [new Paragraph(name)],
}),
]
: []),
new TableCell({ children: [new Paragraph(item)] }),
],
}),
),
),
});
const doc = new Document({
sections: [
{
children: [new Paragraph("If a group doesn't fit at the bottom of a page, all of it moves to the next page."), table],
},
],
});
Table Cells
Cells need to be added in the table row, you can create a table cell like:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const tableCell = new TableCell({
children: [new Paragraph("hello")],
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [new TableRow({ children: [tableCell] })] })],
},
],
});
Or preferably, add the tableRow directly into the table row without declaring a variable:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const tableRow = new TableRow({
children: [
new TableCell({
children: [new Paragraph("hello")],
}),
],
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [tableRow] })],
},
],
});
Options
| Property | Type | Notes |
|---|---|---|
| children | Array<Paragraph or Table> |
Required. You can nest tables by adding a table into a cell |
| shading | IShadingAttributesProperties |
Optional |
| margins | ITableCellMarginOptions |
Optional |
| verticalAlign | VerticalAlignTable |
Optional |
| textDirection | TextDirection |
Optional. BOTTOM_TO_TOP_LEFT_TO_RIGHT or TOP_TO_BOTTOM_RIGHT_TO_LEFT turns the text to run vertically |
| columnSpan | number |
Optional |
| rowSpan | number |
Optional |
| borders | BorderOptions |
Optional |
| width | { size: number type: WidthType } |
Optional |
Border Options
| Property | Type | Notes |
|---|---|---|
| top | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional |
| bottom | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional |
| left | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional |
| right | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional |
| diagonalDown | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional. A line from the top left corner to the bottom right (w:tl2br) |
| diagonalUp | { style: BorderStyle, size: number, color: string | ThemeColor } |
Optional. A line from the bottom left corner to the top right (w:tr2bl) |
Example
import { BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [new Paragraph("Hello")],
borders: {
top: {
style: BorderStyle.DASH_DOT_STROKED,
size: 1,
color: "ff0000",
},
bottom: {
style: BorderStyle.THICK_THIN_MEDIUM_GAP,
size: 5,
color: "889900",
},
},
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
},
],
});
Google DOCS
Google DOCS does not support start and end borders, instead they use left and right borders. So to set left and right borders for Google DOCS you should use:
import { BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [new Paragraph("Hello")],
borders: {
left: {
style: BorderStyle.DOT_DOT_DASH,
size: 3,
color: "00FF00",
},
right: {
style: BorderStyle.DOT_DOT_DASH,
size: 3,
color: "ff8000",
},
},
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
},
],
});
Diagonal borders
diagonalDown draws a line across the cell from its top left corner to its bottom right, and diagonalUp one from its bottom left corner to its top right. They are Word's Diagonal Down Border and Diagonal Up Border.
A diagonal down border splits a header cell in two: a label for the columns above the line, and one for the rows below it. Put the columns' label in a paragraph aligned right, and the rows' label in the paragraph after it.
import { AlignmentType, BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = (text: string) => new TableCell({ children: [new Paragraph(text)] });
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [
new Paragraph({ text: "Subject", alignment: AlignmentType.RIGHT }),
new Paragraph("Student"),
],
borders: {
diagonalDown: { style: BorderStyle.SINGLE, size: 4, color: "000000" },
},
}),
cell("Maths"),
cell("Physics"),
],
}),
new TableRow({ children: [cell("Ada"), cell("92"), cell("88")] }),
new TableRow({ children: [cell("Grace"), cell("85"), cell("91")] }),
],
columnWidths: [2400, 1600, 1600],
}),
],
},
],
});
A cell merged with columnSpan or rowSpan has one diagonal, from corner to corner of the whole merged cell.
Word draws diagonal borders. LibreOffice and Apple Pages don't, and neither does the preview on this page, so download the document to see them.
Add paragraph to a cell
Once you have got the cell, you can add data to it:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [new Paragraph("Hello")],
});
const doc = new Document({
sections: [
{
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
},
],
});
Set width of a cell
You can specify the width of a cell using:
const cell = new TableCell({
...,
width: {
size: number,
type: WidthType,
},
});
WidthType values can be:
| Property | Notes |
|---|---|
| AUTO | |
| DXA | Value is in twentieths of a point |
| NIL | Is considered as zero |
| PERCENTAGE | Percent of table width |
Nested Tables
To have a table within a table, simply add it in the children block of a table cell:
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Inner cell 1")] }),
new TableCell({ children: [new Paragraph("Inner cell 2")] }),
],
}),
],
}),
],
});
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Outer cell")] }), cell] })],
}),
],
},
],
});
Vertical Align
Sets the vertical alignment of the contents of the cell
const cell = new TableCell({
...,
verticalAlign: VerticalAlignTable,
});
VerticalAlign values can be:
| Property | Notes |
|---|---|
| BOTTOM | Align the contents on the bottom |
| CENTER | Align the contents on the center |
| TOP | Align the contents on the top. The default |
For example, to center align a cell:
import { Document, Paragraph, Table, TableCell, TableRow, VerticalAlignTable } from "docx";
const cell = new TableCell({
children: [new Paragraph("Centered")],
verticalAlign: VerticalAlignTable.CENTER,
});
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Line 1"), new Paragraph("Line 2"), new Paragraph("Line 3")] }),
cell,
],
}),
],
}),
],
},
],
});
Merging cells together
Row Merge
When cell rows are merged, it counts as multiple rows, so be sure to remove excess cells. It is similar to how HTML's rowspan works.
https://www.w3schools.com/tags/att_td_rowspan.asp
docx adds a cell to each row below the first for the merged cell, as Word writes a merge. Those cells take the merged cell's width, borders, shading, margins, text direction and vertical alignment, and when the merged cell ends with a paragraph rather than a table, their paragraphs take that paragraph's alignment, so Word treats the merged cell as one when it lays it out and when you select it.
const cell = new TableCell({
...,
rowSpan: [NUMBER_OF_CELLS_TO_MERGE],
});
Example
The example will merge three rows together.
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [new Paragraph("Merged across three rows")],
rowSpan: 3,
});
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
new TableRow({ children: [cell, new TableCell({ children: [new Paragraph("Row 1")] })] }),
// The merged cell takes the first place in the next two rows, so they have one cell each
new TableRow({ children: [new TableCell({ children: [new Paragraph("Row 2")] })] }),
new TableRow({ children: [new TableCell({ children: [new Paragraph("Row 3")] })] }),
],
}),
],
},
],
});
Merge cells by hand
rowSpan writes the merged cell as a cell in each of its rows, and docx adds the ones below the first, with no settings of their own. They take the table's margins, so each row below is at least as tall as the table's margins above and below. To give the merged cell's part in each row settings of its own, such as its margins or borders, write each part yourself with verticalMerge: VerticalMergeType.RESTART on the first, and VerticalMergeType.CONTINUE on each one below, in its own row. Their text goes in the first. Leave out rowSpan when you merge cells by hand.
Here the table's margins are 720 twips, and the rows below the first are kept to a line by giving the merged cell no margins in them:
import { Document, Paragraph, Table, TableCell, TableRow, VerticalMergeType } from "docx";
const noMargins = { top: 0, bottom: 0, left: 0, right: 0 };
const table = new Table({
margins: { top: 720, bottom: 720, left: 720, right: 720 },
rows: [
new TableRow({
children: [
new TableCell({ verticalMerge: VerticalMergeType.RESTART, children: [new Paragraph("I like big margins")] }),
new TableCell({ children: [new Paragraph("Not gonna lie")] }),
],
}),
new TableRow({
children: [
// The merged cell's part in this row, with no margins, so the row is a line tall
new TableCell({ verticalMerge: VerticalMergeType.CONTINUE, margins: noMargins, children: [] }),
new TableCell({ margins: noMargins, children: [new Paragraph("No margins plz")] }),
],
}),
],
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Column Merge
When cell columns are merged, it counts as multiple columns, so be sure to remove excess cells. It is similar to how HTML's colspan works.
https://www.w3schools.com/tags/att_td_colspan.asp
const cell = new TableCell({
...,
columnSpan: [NUMBER_OF_CELLS_TO_MERGE],
});
Example
The example will merge three columns together.
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const cell = new TableCell({
children: [new Paragraph("Merged across three columns")],
columnSpan: 3,
});
const doc = new Document({
sections: [
{
children: [
new Table({
rows: [
new TableRow({ children: [cell] }),
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Column 1")] }),
new TableCell({ children: [new Paragraph("Column 2")] }),
new TableCell({ children: [new Paragraph("Column 3")] }),
],
}),
],
}),
],
},
],
});
Visual Right to Left Table
It is possible to reverse how the cells of the table are displayed. The table direction. More info here: https://superuser.com/questions/996912/how-to-change-a-table-direction-in-microsoft-word
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("1")] }),
new TableCell({ children: [new Paragraph("2")] }),
new TableCell({ children: [new Paragraph("3")] }),
],
}),
],
visuallyRightToLeft: true,
});
const doc = new Document({
sections: [
{
children: [table],
},
],
});
Table Look (Conditional Formatting)
Control which conditional formatting from a table style is applied. Table styles can define special formatting for the first row, first column, etc. Use tableLook to toggle these formatting options.
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
import * as fs from "fs";
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Header 1")] }),
new TableCell({ children: [new Paragraph("Header 2")] }),
new TableCell({ children: [new Paragraph("Header 3")] }),
],
}),
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Row 1, Col 1")] }),
new TableCell({ children: [new Paragraph("Row 1, Col 2")] }),
new TableCell({ children: [new Paragraph("Row 1, Col 3")] }),
],
}),
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Row 2, Col 1")] }),
new TableCell({ children: [new Paragraph("Row 2, Col 2")] }),
new TableCell({ children: [new Paragraph("Row 2, Col 3")] }),
],
}),
],
// A table style from the document's styles, here the ones in demo/assets/custom-styles.xml
style: "MyCustomTableStyle",
tableLook: {
firstRow: true, // Apply first row formatting
lastRow: false, // Don't apply last row formatting
firstColumn: true, // Apply first column formatting
lastColumn: false, // Don't apply last column formatting
noHBand: false, // Apply horizontal banding (row stripes)
noVBand: true, // Don't apply vertical banding (column stripes)
},
});
const doc = new Document({
externalStyles: fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8"),
sections: [
{
children: [table],
},
],
});
Note: When tableLook is not specified at all, Word applies row and column banding by default, but does not apply first/last row/column formatting.
Options
| Property | Type | Description |
|---|---|---|
| firstRow | boolean |
Apply special formatting to first row |
| lastRow | boolean |
Apply special formatting to last row |
| firstColumn | boolean |
Apply special formatting to first column |
| lastColumn | boolean |
Apply special formatting to last column |
| noHBand | boolean |
Disable horizontal banding (row stripes) |
| noVBand | boolean |
Disable vertical banding (column stripes) |
Example
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/table-look.ts
Examples
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/basic-table.ts
Custom borders
Example showing how to add colorful borders to tables
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/table-cell-borders.ts
Adding images
Example showing how to add images to tables
Source: https://github.com/dolanmiu/docx/blob/master/demo/images/image-in-table-cell.ts
Source: https://github.com/dolanmiu/docx/blob/master/demo/images/image-in-header-table-cell.ts
Alignment of text in a cell
Example showing how align text in a table cell
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/cell-alignment-and-text-direction.ts
Shading
Example showing merging of columns and rows and shading
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/merge-and-shade-cells.ts
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/merge-many-cells.ts
Merging columns
Example showing merging of columns and rows
Source: https://github.com/dolanmiu/docx/blob/master/demo/images/image-in-merged-table-cell.ts
Floating tables
A table with float floats: it's placed against the page, the margins or the text, and the text flows around it.
Word can't float a table in line with the text. It places a floating table lined up inline down the page at the top of the paragraph after it, with text beside it. So a table with relativeVerticalPosition: RelativeVerticalPosition.INLINE is written in line with the text instead, as Word writes a table with no text wrapping, and the rest of float is left out. Its relativeHorizontalPosition lines it up across the column: LEFT, CENTER and RIGHT give it that alignment, unless it has an alignment of its own.
Source: https://github.com/dolanmiu/docx/blob/master/demo/tables/floating-tables.ts