Table (6)
Set Table Borders, Column Widths and Table Styles with JavaScript in React
2026-11-25 06:27:42 Written by Amy ZhaoTables generated by code often come with only the default thin lines, and column widths are divided evenly by content, which reads less clearly than a manually typeset table. Fixing the steps for adjusting borders, column widths and styles in code keeps exported documents consistent with the business template and saves the effort of reworking every table in Word after each generation.
This article uses Spire.Doc for JavaScript to set table borders, column widths and table styles directly in the browser. The whole process runs on WebAssembly in the browser, with no Office installation and no backend service, so the document stays on the user's device the entire time.
This article covers three core features:
The scope of the three can be summarised in the table below. Direct formatting takes precedence over the table style, so setting them in a different order produces a different final appearance:
| Setting | Main APIs | Scope |
|---|---|---|
| Table borders | SetBorders / SetBorder / CellFormat.Borders |
The outer frame, the inner grid lines and a single edge |
| Column widths | SetColumnWidth / Cell.Width |
The width and layout of each column |
| Table style | ApplyStyle + StyleOptions |
A preset combination of shading, borders and fonts |
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume that Spire.Doc is installed and the WebAssembly module is initialized. The sample document is a channel sales report, TableFormattingReport.docx, and all three examples work on its first table.
Set Table Borders
Table borders are set with Table.SetBorders() and Table.SetBorder(). The former writes the four edges and the inner grid lines in one call, which suits a uniform appearance; the latter handles only one outer edge of the table. Line widths are in points, and colours use a Color object:
| Method | Purpose |
|---|---|
table.SetBorders(style, width, color) |
Sets the four edges and the inner grid lines at the same time |
table.SetBorder(position, style, width, color, override) |
Sets only the specified table edge |
cell.CellFormat.Borders.Bottom |
Controls the border of an individual cell |
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document, create a
Documentobject and load the file. - Take the first table in the body of the first section.
- Use
Table.SetBorders()to set uniform grid lines, then thicken the bottom border of the header cells. - Use
Document.SaveToFile()to save the result, read the file from the VFS and trigger a browser download.
The code for setting table borders is as follows:
function App() {
const setTableBorders = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample document
await window.spire.FetchFileToVFS('TableFormattingReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
// Create a Document instance and load the document
const doc = new docModule.Document();
doc.LoadFromFile('TableFormattingReport.docx');
const body = doc.Sections.get_Item(0).Body;
const table = body.Tables.get_Item(0);
const navy = docModule.Color.FromArgb(255, 0, 82, 155);
// Four edges and inner grid lines: single line, 1 point, dark blue
table.SetBorders(docModule.BorderStyle.Single, 1, navy);
// Thicken the header bottom border to 2 points separately
const header = table.Rows.get_Item(0);
for (let c = 0; c < header.Cells.Count; c++) {
const border = header.Cells.get_Item(c).CellFormat.Borders.Bottom;
border.BorderType = docModule.BorderStyle.Single;
border.LineWidth = 2;
border.Color = navy;
}
// Save the result file
const outputFileName = 'TableFormattingBordered.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Set Table Borders</h1>
<button onClick={setTableBorders}>Apply</button>
</div>
);
}
export default App;
The table before and after setting the borders is shown below. On the left is the original table, which has only a thin line under the header; on the right, a full set of 1-point dark blue grid lines has been added and the header bottom border thickened to 2 points:

Add a Bottom Border to the Header Only
SetBorder() targets the outer edges of the table; setting BorderPositions.Bottom to 2 points thickens the bottom edge of the whole table, not the line under the header. To emphasise the boundary between the header and the content, set the bottom border of the first-row cells one by one:
// Thicken the bottom border of the header row; the table bottom edge stays unchanged
const header = table.Rows.get_Item(0);
for (let c = 0; c < header.Cells.Count; c++) {
const border = header.Cells.get_Item(c).CellFormat.Borders.Bottom;
border.BorderType = docModule.BorderStyle.Single;
border.LineWidth = 2;
border.Color = docModule.Color.FromArgb(255, 0, 82, 155);
}
Remove the Left and Right Outer Borders
When the table has to sit flush with the text area, the inner vertical lines can be kept while the left and right outer borders are switched off separately. In the JavaScript version, passing BorderStyle.None to Table.SetBorder() does not rewrite the table border; the reliable approach is to modify the left and right edges in the table format directly:
// Switch off the left and right outer borders; other edges and inner grid lines are unaffected
table.Format.Borders.Left.BorderType = docModule.BorderStyle.None;
table.Format.Borders.Right.BorderType = docModule.BorderStyle.None;
Cell Borders Take Precedence over Table Borders
A cell can carry its own border, which takes precedence over the table-level border when displayed. If individual cells still keep their original thin lines after SetBorders() is called, those cells have usually had their borders set separately before; clear the cell borders one by one and then write the table borders again.
Set Column Widths
Column widths are adjusted with Table.SetColumnWidth(), which sets the width by column index. The second argument is the width value, and the third argument, WidthType, determines how the width is stored:
| Enum value | How the width is written | Description |
|---|---|---|
WidthType.Twip |
Points | An absolute width, converted to twips when saved (1 point = 20 twips) |
WidthType.Percentage |
Percentage | Calculated relative to the table width, so columns scale with the table |
WidthType.Auto |
Decided by content | Left to Word's automatic layout |
AutoFit has to be turned off before the call; otherwise Word redistributes the column widths by content and overwrites the values set by hand.
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document, create a
Documentobject and load the file. - Take the target table and turn off
Format.AllowAutoFit. - Use
Table.SetColumnWidth()to set the width of each column. - Save the result, read the file from the VFS and trigger a browser download.
The code for setting column widths is as follows:
function App() {
const setColumnWidth = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample document
await window.spire.FetchFileToVFS('TableFormattingReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
// Create a Document instance and load the document
const doc = new docModule.Document();
doc.LoadFromFile('TableFormattingReport.docx');
const body = doc.Sections.get_Item(0).Body;
const table = body.Tables.get_Item(0);
// Turn off AutoFit so that the column widths are not redistributed by content
table.Format.AllowAutoFit = false;
// Set the width of the five columns in points
table.SetColumnWidth(0, 90, docModule.WidthType.Twip);
table.SetColumnWidth(1, 120, docModule.WidthType.Twip);
table.SetColumnWidth(2, 70, docModule.WidthType.Twip);
table.SetColumnWidth(3, 70, docModule.WidthType.Twip);
table.SetColumnWidth(4, 120, docModule.WidthType.Twip);
// Save the result file
const outputFileName = 'TableFormattingSized.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Set Column Widths</h1>
<button onClick={setColumnWidth}>Apply</button>
</div>
);
}
export default App;
The table before and after adjusting the column widths is shown below. On the left is the original content-based distribution; on the right, AutoFit is turned off and the five columns are redistributed, with the first column widened and the last narrowed:

Column Widths Do Not Change After Setting
The most common cause is that the table is still in AutoFit mode. When Format.AllowAutoFit is true, Word redistributes the column widths by content and overrides the values set by hand, so AutoFit has to be turned off before the widths are set. Another cause is that the sum of the column widths exceeds the available table width; Word then compresses all columns proportionally, so the result does not match the values that were set.
Percentage or Points
Percentage widths are calculated relative to the table width and suit layouts that have to scale with the text area; points are absolute and suit alignment with a fixed text area. When percentages are used, the table itself needs a definite width first, or Word may compress the whole table into a very narrow column. Mixing the two units within one table is not recommended: when the table width changes, the point-based columns stay the same while the percentage-based columns change, and the proportions become unbalanced.
Set Cell Widths One by One
Besides setting widths by column, each cell can be given its own width. Cell.Width is in points, which suits layouts that need different widths within a column:
// After turning off AutoFit, set the width of each cell (in points)
table.Format.AllowAutoFit = false;
for (let r = 0; r < table.Rows.Count; r++) {
const row = table.Rows.get_Item(r);
row.Cells.get_Item(0).Width = 90;
row.Cells.get_Item(4).Width = 120;
}
Per-cell settings and per-column settings can be combined: first use SetColumnWidth() to fix the overall proportions, then fine-tune individual cells with Cell.Width.
Apply a Table Style
Table styles are applied with Table.ApplyStyle() and Table.Format.StyleName. A built-in style packages borders, shading and font colours into a preset, and StyleOptions decides whether options in the preset, such as first-row emphasis and row banding, take effect:
| Member | Description |
|---|---|
table.ApplyStyle({ builtinTableStyle }) |
Applies a built-in table style; the object form is required |
table.Format.StyleOptions |
Combines options such as FirstRow and RowStripe |
table.Format.StyleName |
Reads the name of the current style |
table.Format.ClearFormatting() |
Clears direct formatting so that the style can take effect |
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document, create a
Documentobject and load the file. - Take the target table and clear the direct formatting on it.
- Use
Table.ApplyStyle()to apply the target style, then setStyleOptions. - Save the result, read the file from the VFS and trigger a browser download.
The code for applying a table style is as follows:
function App() {
const applyTableStyle = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample document
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
await window.spire.FetchFileToVFS('TableFormattingReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
// Create a Document instance and load the document
const doc = new docModule.Document();
doc.LoadFromFile('TableFormattingReport.docx');
const body = doc.Sections.get_Item(0).Body;
const table = body.Tables.get_Item(0);
// Clear shading and borders set by hand so that direct formatting does not override the style
table.Format.ClearFormatting();
// Apply a built-in style: specify the style source with the object form
table.ApplyStyle({
builtinTableStyle: docModule.DefaultTableStyle.LightShadingAccent1,
});
// Enable the first row, first column and row banding
table.Format.StyleOptions = docModule.TableStyleOptions.Default;
// Save the result file
const outputFileName = 'TableFormattingStyled.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Apply a Table Style</h1>
<button onClick={applyTableStyle}>Apply</button>
</div>
);
}
export default App;
The table before and after applying the style is shown below. On the left is the original table before the direct formatting is cleared; on the right, LightShadingAccent1 has been applied and first-row emphasis and row banding appear:

Nothing Changes After the Style Is Applied
A style usually fails to take effect for two reasons. First, the table carries directly set shading or borders, and direct formatting takes precedence over the style; clear it with Format.ClearFormatting() first, or clear the corresponding formats item by item. Second, passing the enum to ApplyStyle() directly triggers an overload ambiguity, so the object form { builtinTableStyle: ... } should be used instead. In addition, the combination of the chosen style and StyleOptions determines whether first-row emphasis and row banding appear; after applying, check whether Format.StyleName has switched to the target style.
Styles or Custom Borders
Built-in styles make it easy to keep a consistent look, but the room for adjustment is limited. Formal reports usually take the approach of "a style as the base, borders for fine tuning": apply a style first to get the shading and fonts, then adjust the key dividing lines with SetBorders() or SetBorder(). In this way the style carries the overall appearance, the borders only cover the lines that need emphasis, the scope of adjustment is smaller, and later bulk changes are easier.
Order of the Three Settings
| Step | Call | Purpose |
|---|---|---|
| Apply the style | ApplyStyle + StyleOptions |
Shading, fonts and the overall look |
| Fix column widths | AllowAutoFit = false + SetColumnWidth |
Keep the table aligned with the text area |
| Adjust borders | SetBorders / SetBorder |
Emphasise dividing lines |
The order of style first, then column widths, then borders usually gives the simplest precedence relationships. For a table created by code, borders and column widths are better set after the data has been filled in, because writing content may trigger a new table layout.
FAQ
Why Do Cells Still Keep Their Original Thin Lines After Setting Table Borders
Cause: SetBorders() sets table-level borders, while a border carried by the cell itself is displayed first. If the table in the sample document had cell borders set separately before, the original lines remain.
Fix: Clear the cell borders one by one and then write the table borders again; alternatively, set CellFormat.Borders on the target cells directly so that the cell borders match the table borders.
Why Does the Table Stay the Same After the Column Widths Are Adjusted
Cause: The table is still in AutoFit mode, or the sum of the column widths exceeds the available table width. The former makes Word redistribute the widths by content, and the latter triggers proportional compression.
Fix: Set table.Format.AllowAutoFit = false first, then call SetColumnWidth(); when precise control is needed, set Cell.Width cell by cell instead and make sure the total width does not exceed the text area.
Why Does the Table Look Different from What Was Expected After a Built-in Style Is Applied
Cause: The table carries directly set shading, borders or cell widths, and direct formatting takes precedence over the style, so the first-row emphasis and row banding in the style do not show.
Fix: Clear the direct formatting with Format.ClearFormatting() first, apply the style with the object form { builtinTableStyle: ... }, and set StyleOptions = TableStyleOptions.Default; after applying, confirm with Format.StyleName that the style name has changed.
Can a Border Be Added to the Header or a Single Row Only
Yes. SetBorder() targets the outer edges of the whole table, whereas a border on the header or a single row is a cell-level setting. Walk the cells of the target row and modify the corresponding edge in CellFormat.Borders, for example to thicken only the bottom border of the header row.
Do Setting Borders, Column Widths and Styles Change the Text in the Table
These methods change layout attributes only. SetBorders, SetColumnWidth and ApplyStyle in this article work on borders, column widths and styles; they do not touch the text content, paragraph structure or data order in the cells.
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Delete, Copy and Export Table Structures with JavaScript in React
2026-11-24 02:07:13 Written by Amy ZhaoSample tables left behind in a template need cleaning up, summary rows in a report need to be copied to a given position, and data analysis calls for a table to be turned into CSV for other tools. The three operations work on different levels: deletion targets the table object itself, copying targets the row and cell collections, and export has to read every cell and cope with the column misalignment that merged cells cause.
This article uses Spire.Doc for JavaScript to perform all three operations directly in the browser. The whole process runs on WebAssembly in the browser, documents are read and written through a virtual file system (VFS), and there is no Office installation and no backend, so the file stays on the user's device the entire time.
This article covers three features:
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume that Spire.Doc is installed and the WebAssembly module is initialized.
Delete Tables from a Document
The body of a Spire.Doc document is a sequence of paragraphs, tables and other objects, and Body.ChildObjects gives access to them one by one. Every object carries a DocumentObjectType property, and comparing it with DocumentObjectType.Table tells whether the object is a table. There are two ways to delete a table: remove it by object, which suits the case where the target table is known, and remove it by index, which suits a batch operation such as "delete every table".
The relationship between tables, rows and cells is as follows:
| Level | How it is accessed | Common members |
|---|---|---|
| Table | Body.ChildObjects, Body.Tables |
RemoveAt, Remove, Count |
| Row | Table.Rows |
Add, Insert, RemoveAt |
| Cell | TableRow.Cells |
Insert, RemoveAt, GridSpan |
| Row copy, cell copy | TableRow.Clone(), TableCell.Clone() |
The formatting is copied along with the content |
Body.Tables counts every table in the body, including a 1×1 single-cell table; when the position in document order matters, go by Body.ChildObjects.
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document, create a
Documentobject and load the file. - Take the body of the first section and walk
Body.ChildObjectsbackwards. - Check the
DocumentObjectTypeof the object and callRemoveAton the tables. - Save the result with
Document.SaveToFile(), read the file from the VFS and trigger a browser download.
The code for deleting the tables in a document is as follows:
function App() {
const deleteTables = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample document
await window.spire.FetchFileToVFS('QuarterlyReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('QuarterlyReport.docx');
const body = doc.Sections.get_Item(0).Body;
// Delete every table backwards so that no index is skipped
for (let i = body.ChildObjects.Count - 1; i >= 0; i--) {
const obj = body.ChildObjects.get_Item(i);
if (obj.DocumentObjectType === docModule.DocumentObjectType.Table) {
body.ChildObjects.RemoveAt(i);
}
}
const outputFileName = 'TablesRemoved.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the result file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Delete Tables in the Document</h1>
<button onClick={deleteTables}>Delete</button>
</div>
);
}
export default App;
Delete tables from a document: page 1 before (left) and after all tables are removed (right):

Five tables are removed from the document, including the 1×1 summary box at the top of the page; the title, the body paragraphs, the header and the footer are all left unchanged.
Delete Only the Specified Table
When the other tables have to stay, read the text of the first cell of the first row before deleting and use it as the criterion. The first cell of the registration table in the appendix holds "Channel Name", so only that table is deleted:
// Walk backwards and pick the table to delete by the text of its first header cell
for (let i = body.ChildObjects.Count - 1; i >= 0; i--) {
const obj = body.ChildObjects.get_Item(i);
if (obj.DocumentObjectType !== docModule.DocumentObjectType.Table) continue;
const cell = obj.Rows.get_Item(0).Cells.get_Item(0);
const label = cell.ChildObjects.get_Item(0).Text || '';
if (label.indexOf('Channel Name') >= 0) {
body.ChildObjects.RemoveAt(i);
}
}
When a forward loop reads and deletes at the same time, the index of every following object shifts after a deletion and an adjacent table may be skipped, so a batch deletion is better walked backwards. After a table is removed, the empty paragraph that used to sit next to it is still there; to get rid of the extra blank line, check after the deletion whether the neighbouring paragraph is empty.
Copy Table Rows and Columns
Copying rows and columns differs in one respect: a row has a ready-made method — TableRow.Clone() gives a copy of the row and Table.Rows.Insert(index, row) puts it in place. The table model has no "column object", so copying a column means cloning the cell of every row and inserting it with Cells.Insert(index, cell). The clone carries the formatting of the cell with it.
| Operation | Main calls | Notes |
|---|---|---|
| Copy a row | TableRow.Clone() + Table.Rows.Insert(index, row) |
The copy keeps the formatting inside the row |
| Append a row | TableRow.Clone() + Table.Rows.Add(row) |
The copy goes to the end of the table |
| Copy a column | TableCell.Clone() + Cells.Insert(index, cell) |
Inserted row by row; the column width has to be set separately |
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document, create a
Documentobject and load the file. - Take the target table, clone row 2 and insert it after the original row with
Table.Rows.Insert(). - Clone the cells of column 2 row by row and insert them as the new column 3 with
Cells.Insert(). - Save the result file, read it from the VFS and trigger a browser download.
The code for copying the table row and column is as follows:
function App() {
const copyRowAndColumn = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
await window.spire.FetchFileToVFS('QuarterlyReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('QuarterlyReport.docx');
const body = doc.Sections.get_Item(0).Body;
// The first table is the 1×1 summary box, so the summary table sits at index 1
const table = body.Tables.get_Item(1);
// Copy row 2 (index 1) and insert it after the original row
const rowCopy = table.Rows.get_Item(1).Clone();
table.Rows.Insert(2, rowCopy);
// Copy column 2 (index 1) and insert it row by row as the new column 3
for (let r = 0; r < table.Rows.Count; r++) {
const row = table.Rows.get_Item(r);
row.Cells.Insert(2, row.Cells.get_Item(1).Clone());
}
// The new column keeps the width of the column it was copied from; set it to 120 pt cell by cell where needed
for (let r = 0; r < table.Rows.Count; r++) {
table.Rows.get_Item(r).Cells.get_Item(2).Width = 120;
}
const outputFileName = 'TableCopied.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the result file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Copy Table Rows and Columns</h1>
<button onClick={copyRowAndColumn}>Copy</button>
</div>
);
}
export default App;
The summary table after the row and column copy: row 2 (index 1) is duplicated and a column is inserted after column 2.

Adjust the Column Width After Copying
A cloned cell keeps its own width, so the new column inherits the width of the column it was copied from. In the sample the copied second column is about 85 pt wide, while the first column is about 111 pt and the fourth about 102 pt, so the inserted column looks narrow; TableCell.Width is measured in points, and setting it cell by cell adjusts the column as needed:
// Set the new column to 120 pt; every cell has to be set separately
for (let r = 0; r < table.Rows.Count; r++) {
table.Rows.get_Item(r).Cells.get_Item(2).Width = 120;
}
After the row copy is inserted the table goes from 5 rows to 6, and after the column copy is inserted and its width set every row goes from 5 cells to 6. After a copy it is worth re-reading Table.Rows.Count and Cells.Count to confirm that the structure is the expected one.
Export Tables to CSV
The rules for exporting a table as CSV are simple: fields are separated by commas, a field that contains a comma, a double quote or a line break is wrapped in double quotes, and a double quote inside a field is written twice. The difficulty lies in the merged cells: a horizontal merge folds several columns into one cell, a vertical merge leaves the following rows with continuation cells that hold no text, and joining the fields by Cells.Count directly misaligns the columns.
TableCell.GridSpan gives the number of columns a cell occupies (1 for an ordinary cell); accumulating the column index by the span puts every field back into its original column:
| Property | Meaning | Use in the export |
|---|---|---|
GridSpan |
Number of columns the cell occupies | Accumulate the column index and handle horizontal merges |
CellFormat.HorizontalMerge |
State of the horizontal merge | Tell the starting cell from the continuation cells |
CellFormat.VerticalMerge |
State of the vertical merge | Detect a continuation cell and take the value of the row above |
CellMerge.Continue |
Continuation state of a vertical merge | Fill the cell with the value of the same column in the row above |
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document and the fonts, create a
Documentobject and load the file. - Walk every section and every body object, and add up the real column count of each table by
GridSpan. - Read the text of the cells row by row, escape it by the CSV rules and write it into the right column.
- Put a UTF-8 BOM in front of the content, write the file into the VFS and trigger the download.
The code for exporting the tables to CSV is as follows:
function App() {
const exportTablesToCsv = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check whether the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
await window.spire.FetchFileToVFS('QuarterlyReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('QuarterlyReport.docx');
// Escape a field by the CSV rules
const csvEscape = (value) => {
const text = String(value).replace(/"/g, '""');
return /[",\r\n]/.test(text) ? `"${text}"` : text;
};
// Read the text of every paragraph in the cell
const getCellText = (cell) => {
let text = '';
for (let k = 0; k < cell.ChildObjects.Count; k++) {
const child = cell.ChildObjects.get_Item(k);
if (child.DocumentObjectType === docModule.DocumentObjectType.Paragraph) {
text += child.Text;
}
}
return text.replace(/[\r\n]+/g, ' ').trim();
};
let csv = '';
for (let s = 0; s < doc.Sections.Count; s++) {
const body = doc.Sections.get_Item(s).Body;
for (let i = 0; i < body.ChildObjects.Count; i++) {
const obj = body.ChildObjects.get_Item(i);
if (obj.DocumentObjectType !== docModule.DocumentObjectType.Table) continue;
// Add up the real column count of each row by GridSpan
let maxColumns = 0;
for (let r = 0; r < obj.Rows.Count; r++) {
const row = obj.Rows.get_Item(r);
let columns = 0;
for (let c = 0; c < row.Cells.Count; c++) {
columns += row.Cells.get_Item(c).GridSpan || 1;
}
maxColumns = Math.max(maxColumns, columns);
}
// Write the fields row by row; a merged cell takes its span of slots
for (let r = 0; r < obj.Rows.Count; r++) {
const row = obj.Rows.get_Item(r);
const fields = new Array(maxColumns).fill('');
let column = 0;
for (let c = 0; c < row.Cells.Count; c++) {
const cell = row.Cells.get_Item(c);
fields[column] = csvEscape(getCellText(cell));
column += cell.GridSpan || 1;
}
csv += fields.join(',') + '\r\n';
}
// Leave a blank line between tables so that they stay apart
csv += '\r\n';
}
}
// Write a UTF-8 BOM so that Excel recognises the text correctly
const BOM = '\uFEFF';
window.dotnetRuntime.Module.FS.writeFile('Tables.csv', BOM + csv);
const fileArray = window.dotnetRuntime.Module.FS.readFile('Tables.csv');
const blob = new Blob([fileArray], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Tables.csv';
a.click();
URL.revokeObjectURL(url);
doc.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Export Tables to CSV</h1>
<button onClick={exportTablesToCsv}>Export</button>
</div>
);
}
export default App;
The exported Tables.csv: horizontally merged cells expand into placeholder columns and the columns stay aligned.

The sample document holds 5 tables and the export gives 21 rows of data. The horizontally merged Total row and the two-row header both expand into placeholder columns and the columns stay aligned; the file starts with a BOM, so the text displays correctly when it is opened directly in Excel.
Handle Merged Cells
The cell of a horizontal merge only appears in its starting column, and GridSpan gives the number of columns it occupies. In the sample the span of Expenses (¥10k) is 2, so after accumulating the column index, Share of Sales is written back to column 4 and the exported row reads Channel,Expenses (¥10k),,Share of Sales, with column 3 left empty to mark the extension of the merged area.
const cell = row.Cells.get_Item(c);
fields[column] = csvEscape(getCellText(cell));
column += cell.GridSpan || 1;
The starting cell of a vertical merge carries the text and the continuation cells are empty. To fill the value of a merged area into every row, compare CellFormat.VerticalMerge with CellMerge.Continue and take the value of the same column from the previous row:
// previousRow is the fields array of the previous row
const isContinue =
cell.CellFormat.VerticalMerge === docModule.CellMerge.Continue;
fields[column] = isContinue ? previousRow[column] : csvEscape(getCellText(cell));
In the sample the Region column merges four cells in two groups vertically, and after the fill every row carries its region name; the vertically merged Channel and Share of Sales headers repeat on the second header row as well. Whether to fill depends on what the data is for: keeping the blanks stays closer to the original table, while the filled result is easier to import into a database or to analyse with a pivot table.
FAQ
Why Is the First Table of Body.Tables Not the One to Work On
Cause: Body.Tables counts every table in the body, including the 1×1 single-cell tables used for layout. In the sample the summary box sits at index 0, while the channel summary table actually sits at index 1.
Fix: confirm the target table by the text of its first header cell first, or walk Body.ChildObjects, filter the objects by DocumentObjectType and count the tables in document order.
Is the Text Inside a Table Kept After the Table Is Deleted
The text goes away with the table object, and the paragraphs outside the table are not affected. After all tables are deleted the title, the body and the footer are still there, and the space the tables used is released with them.
The Copied Column Width Does Not Match the Adjacent Column; How Can It Be Adjusted
The new column takes the width of the cell it was cloned from, so whether it matches the neighbouring columns depends on the width of the original column. In the sample the copied second column is about 85 pt and the first column is about 111 pt, which is why the new column looks narrower. Setting Cell.Width (in points) on every cell adjusts it as needed:
for (let r = 0; r < table.Rows.Count; r++) {
table.Rows.get_Item(r).Cells.get_Item(2).Width = 120;
}
Why Does the Exported CSV Show Garbled Characters in Excel
Cause: a CSV file carries no encoding information of its own, and Excel parses it with the local system encoding, so text encoded in UTF-8 shows up garbled.
Fix: prepend a UTF-8 BOM ('\uFEFF') to the content before writing it; alternatively import the file in Excel through Data > From Text/CSV and choose UTF-8 during the import.
Why Are the Columns Misaligned After Merged Cells Are Exported
Cause: a horizontal merge folds several columns into a single cell, so joining the fields by Cells.Count shifts every following field to the left; the continuation cells of a vertical merge hold no text and are easily mistaken for real empty values.
Fix: accumulate the column index by GridSpan and write every field back to its original column; detect a vertical continuation cell with CellFormat.VerticalMerge === CellMerge.Continue and fill it with the value of the same column in the previous row.
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Insert and Extract Pictures in Word Tables with JavaScript in React
2026-11-23 10:01:23 Written by Amy ZhaoA product catalogue needs an appearance picture for every model, and an inspection record needs a site photo for every step. These pictures do not sit in body paragraphs; they are table content that moves with its row and column. Generating such documents calls for adding pictures into cells, while consolidating data calls for taking existing pictures out as they are, so that an image library or a reporting tool can process them further.
This article uses Spire.Doc for JavaScript to perform both operations in the browser. The process runs on WebAssembly in the browser, and documents are read and written through the virtual file system (VFS); no Office installation or backend service is required, and files always stay on the user's device.
This article covers two core features:
Both operations work on the same object hierarchy, only in opposite directions. A picture is not attached to the cell directly but to a paragraph inside the cell:
| Level | Access | Common members |
|---|---|---|
| Table | Body.Tables, Body.ChildObjects |
Rows, Rows.Count |
| Row | Table.Rows.get_Item(r) |
Cells, Cells.Count |
| Cell | TableRow.Cells.get_Item(c) |
AddParagraph, ChildObjects |
| Paragraph | Cell.AddParagraph() |
AppendPicture, AppendText, ChildObjects |
| Picture | Paragraph.ChildObjects |
ImageBytes, Width, Height |
Insertion walks from the top down to the paragraph and then appends the picture; extraction walks from the bottom up, takes the picture object first, and then names it by the row and column it belongs to.
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume that Spire.Doc is installed and the WebAssembly module is initialized.
Insert Pictures into Cells
The entry point for inserting a picture is the paragraph's AppendPicture() method; the cell itself has no picture method: first add a paragraph with Cell.AddParagraph(), then call the method on that paragraph. The argument has two forms, corresponding to the two sources of a picture file:
| Form | What is inserted |
|---|---|
paragraph.AppendPicture('Product-01.png') |
Reads a picture file from the VFS |
paragraph.AppendPicture({ imageBytes: bytes }) |
Uses picture bytes already in memory |
When no size is set, the picture is displayed by converting its own pixel size at 96 DPI: in the example a 640 × 480 pixel picture comes out as 480 × 360 pt, so Width and Height usually have to be set to align it with the layout.
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document and the product pictures, create a
Documentobject and load the file. - Take the product catalogue table and locate the cell in the "Product Drawing" column row by row.
- Add a paragraph with
Cell.AddParagraph(), callParagraph.AppendPicture()to insert a picture and set its size. - Save the result with
Document.SaveToFile(), read the file from the VFS and trigger a browser download.
The code for inserting pictures into cells is as follows:
function App() {
const insertImagesIntoCells = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample document and the product pictures
await window.spire.FetchFileToVFS('ProductCatalog.docx', '', `${process.env.PUBLIC_URL}/data/`);
const images = [
'Product-01.png', 'Product-02.png', 'Product-03.png',
'Product-04.png', 'Product-05.png', 'Product-06.png',
];
for (const name of images) {
await window.spire.FetchFileToVFS(name, '', `${process.env.PUBLIC_URL}/data/`);
}
const doc = new docModule.Document();
doc.LoadFromFile('ProductCatalog.docx');
// Index 0 is the 1×1 summary box on the cover; the product catalogue is the 2nd table
const table = doc.Sections.get_Item(0).Body.Tables.get_Item(1);
for (let r = 0; r < images.length; r++) {
// Column 6 is the product drawing column; row 1 is the header
const cell = table.Rows.get_Item(r + 1).Cells.get_Item(5);
const paragraph = cell.AddParagraph();
paragraph.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const picture = paragraph.AppendPicture(images[r]);
picture.Width = 90;
picture.Height = 68;
}
const outputFileName = 'CatalogWithImages.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the result file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert Cell Pictures</h1>
<button onClick={insertImagesIntoCells}>Insert Pictures</button>
</div>
);
}
export default App;
Inserting pictures into cells: page 1 before (left) and after (right):

The Product Drawing column of the sample document is originally empty; the six rows are completed in one pass, each picture centred and displayed at 90 × 68 pt. The picture height plus the cell margins exceeds the reserved row height, so the six rows grow taller and the document goes from 3 pages to 4.
Unify Picture Sizes
The row height of a cell is decided by its content; if one picture in a row is taller, the whole row grows with it, and pictures across columns at different sizes leave the row heights uneven. Picture.Width and Height are in points, and setting both forces pictures of different ratios to one size.
When only the width is set, the height is converted automatically by the original ratio: in the example a 640 × 480 picture set to a width of 90 pt becomes 67.5 pt high.
const picture = paragraph.AppendPicture(images[r]);
// Width only: the height is converted automatically (a sample picture set to 90 pt wide becomes 67.5 pt high)
picture.Width = 90;
// Or set both: force pictures of different ratios to one size for a tidier layout
picture.Width = 90;
picture.Height = 68;
Pictures and Text in One Cell
A cell may hold both text and pictures, and their position is decided by the order of the paragraphs. Calling Cell.AddParagraph() twice places the picture above and the text below, which suits caption-style layouts such as "picture + model"; calling AppendText and then AppendPicture in one paragraph arranges them inline in that order, but the picture wraps to the next line when the cell is not wide enough.
// Option 1: two paragraphs, picture above and text below
const cell = table.Rows.get_Item(1).Cells.get_Item(5);
const pPic = cell.AddParagraph();
pPic.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const pic = pPic.AppendPicture('Product-01.png');
pic.Width = 90;
pic.Height = 68;
const pCap = cell.AddParagraph();
pCap.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
pCap.AppendText('HX-TC200');
// Option 2: one paragraph, text and picture side by side
const cell2 = table.Rows.get_Item(2).Cells.get_Item(5);
const pLine = cell2.AddParagraph();
pLine.AppendText('FS-450 ');
const pic2 = pLine.AppendPicture('Product-02.png');
pic2.Width = 40;
pic2.Height = 30;
Picture and text in one cell: picture above text (row 1); text beside picture (row 2):

The two forms differ only in the number of paragraphs: several objects in one paragraph share one inline layout and wrap when they do not fit, while two paragraphs each occupy a line of their own and give more control over position.
Extract Pictures from Tables
Extraction has to go level by level through "table → row → cell → paragraph → picture". The ChildObjects of a cell contains paragraphs and possibly a nested table; pictures are attached to the ChildObjects of a paragraph, their type is DocumentObjectType.Picture, and the original data is provided by ImageBytes.
| Member | Description |
|---|---|
Cell.ChildObjects |
Objects in the cell, which may include a nested table besides paragraphs |
Paragraph.ChildObjects |
Inline objects in the paragraph, such as TextRange and Picture |
DocumentObjectType.Picture |
The type identifier of a picture object |
Picture.ImageBytes |
The original bytes of the picture (Uint8Array) |
Picture.Width, Height |
The display size of the picture (pt) |
Body.Tables counts every table in the body, including 1×1 single-cell tables used for layout; the summary box on the cover of the sample document is such a table, and it has to be counted when tables are taken by index.
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample document and the font, create a
Documentobject and load the file. - Walk the body objects, filter out the tables, then enter paragraphs row by row and cell by cell.
- Check the object type in each paragraph, read
ImageBytesfor pictures and name them by row and column. - Package the pictures as a ZIP and trigger a browser download.
The code for extracting pictures from tables is as follows:
import React from 'react';
import JSZip from 'jszip';
function App() {
const extractImagesFromTables = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
await window.spire.FetchFileToVFS('ProductCatalog.docx', '', `${process.env.PUBLIC_URL}/data/`);
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const doc = new docModule.Document();
doc.LoadFromFile('ProductCatalog.docx');
const zip = new JSZip();
// Walk one table; prefix records its position in the outer table
const walkTable = (table, prefix) => {
for (let r = 0; r < table.Rows.Count; r++) {
const row = table.Rows.get_Item(r);
for (let c = 0; c < row.Cells.Count; c++) {
const cell = row.Cells.get_Item(c);
// A cell may hold several pictures; number them in the order they appear
let index = 0;
for (let k = 0; k < cell.ChildObjects.Count; k++) {
const child = cell.ChildObjects.get_Item(k);
if (child.DocumentObjectType === docModule.DocumentObjectType.Paragraph) {
for (let p = 0; p < child.ChildObjects.Count; p++) {
const item = child.ChildObjects.get_Item(p);
if (item.DocumentObjectType === docModule.DocumentObjectType.Picture) {
index++;
const name = `${prefix}-r${r + 1}c${c + 1}-${index}.png`;
zip.file(name, new Uint8Array(item.ImageBytes));
}
}
} else if (child.DocumentObjectType === docModule.DocumentObjectType.Table) {
// A nested table inside the cell is handled recursively
walkTable(child, `${prefix}-r${r + 1}c${c + 1}.t`);
}
}
}
}
};
const body = doc.Sections.get_Item(0).Body;
let tableIndex = 0;
for (let i = 0; i < body.ChildObjects.Count; i++) {
const obj = body.ChildObjects.get_Item(i);
if (obj.DocumentObjectType !== docModule.DocumentObjectType.Table) continue;
tableIndex++;
walkTable(obj, `table-${tableIndex}`);
}
// Package the pictures as a ZIP and trigger the download
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = 'TableImages.zip';
a.click();
URL.revokeObjectURL(url);
doc.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract Table Pictures</h1>
<button onClick={extractImagesFromTables}>Extract Pictures</button>
</div>
);
}
export default App;
The sample document has 4 tables in its body, and extraction returns 5 pictures: 3 site photos from the inspection record, 1 inspection stamp in the conclusion row, and 1 traceability code inside the nested table of the review record. File names follow the pattern "table number-row-column-sequence", and a picture inside a nested table carries an extra .t segment so that its original position can be traced.
Pictures in Nested Tables
A cell can contain another table, and that table can contain pictures as well. Walking only the paragraphs of outer cells misses this content: the review record in the conclusion row of the sample is a four-row nested table, and the traceability code picture sits in one of its cells. A one-level walk returns 4 pictures; with recursion it returns 5.
// An object in the cell may also be a table; enter it and keep walking
} else if (child.DocumentObjectType === docModule.DocumentObjectType.Table) {
walkTable(child, `${prefix}-r${r + 1}c${c + 1}.t`);
}
During recursion the position of the nested table is joined into the file name: table-3-r6c2.t-r4c2-1.png means the first picture in row 4, column 2 of the nested table inside the cell at row 6, column 2 of the third table.
Picture Formats and File Extensions
ImageBytes returns the original data of the picture as stored in the document, and the format depends on the original file; all pictures in the sample are PNG, with the byte header 89 50 4E 47. If the document stores a JPEG, the header is FF D8 FF, and naming the file .png in that case only helps recognition — some viewers or upload endpoints that validate by extension will reject it. When the exact extension matters, read the magic number at the head of the bytes and decide from it:
const getImageExtension = (bytes) => {
if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'png';
if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'jpg';
if (bytes[0] === 0x47 && bytes[1] === 0x49) return 'gif';
if (bytes[0] === 0x42 && bytes[1] === 0x4d) return 'bmp';
return 'bin';
};
// Name the file with its real format
const ext = getImageExtension(item.ImageBytes);
zip.file(`${prefix}-r${r + 1}c${c + 1}-${index}.${ext}`, new Uint8Array(item.ImageBytes));
FAQ
Why Is the First Table in Body.Tables Not the Product Catalogue
Cause: Body.Tables counts every table in the body, including 1×1 single-cell tables used for layout. The "Summary of This Edition" box on the cover of the sample document is such a table, at index 0, and the product catalogue is actually at index 1.
Fix: read the text of the first cell in the header to confirm the target table, or walk Body.ChildObjects instead, filter tables by DocumentObjectType and count them in order. When body tables and layout tables have to be distinguished in document order, rely on Body.ChildObjects.
Why Do the Table Row Heights and Pagination Change After Pictures Are Inserted
Cause: the row height of a cell is decided by its content; when a picture is taller than the reserved row height, the whole row is stretched and the content after it moves down. In the example the six rows grow slightly taller and the document goes from 3 pages to 4.
Fix: scale the pictures to a uniform size such as 90 × 68 pt before insertion, and reserve the row height above the sum of the picture height and the cell margins, so that the page count changes much less.
Fewer Pictures Are Extracted Than Expected
Cause: a picture may sit in a nested table inside a cell, and walking only the paragraphs of outer cells misses it; if several pictures in one cell use the same file name, later ones overwrite earlier ones when packaging.
Fix: check for DocumentObjectType.Table in the cell walk and recurse into it; number pictures within a cell in the order they appear, e.g. -1, -2 in the example.
A Saved .png Does Not Open in Some Tools
Cause: ImageBytes returns the original data, and the extension does not necessarily match the content. All pictures in the sample are PNG; if a picture is stored as JPEG in the document, its byte header is FF D8 FF, and naming it .png makes strict viewers or upload endpoints reject it.
Fix: read the magic number at the head of the bytes to determine the format and name the file accordingly, as described in "Picture Formats and File Extensions".
Can a Picture from Memory Be Inserted Without a File
Yes. Pass the byte array to AppendPicture({ imageBytes: bytes }); without a size it is likewise converted at 96 DPI. Note that the byte array cannot be passed directly as the argument: that form reports an "ambiguous call", and imageBytes has to be written out to select the matching overload.
const bytes = window.dotnetRuntime.Module.FS.readFile('Product-04.png');
const picture = paragraph.AppendPicture({ imageBytes: bytes });
picture.Width = 90;
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Merging and splitting table cells is one of the most common table editing operations in Word document development — whether creating report headers with cross-column titles or grouping products across rows, cell merging makes table structures clearer and more organized. Spire.Doc for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage fonts and file resources — no backend server required.
This article covers three core features:
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc is installed and the WebAssembly module is initialized.
Merge and Split Cells
A common task in real-world development is adjusting the structure of an existing table: merging adjacent cells into one, or splitting a single cell into multiple rows and columns. Spire.Doc provides ApplyHorizontalMerge, ApplyVerticalMerge, and SplitCell methods for horizontal merging, vertical merging, and splitting respectively. The workflow involves three steps: first, load font files and the target Word file into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the file, retrieve the target table, and call the merge or split methods; finally, save the document, read the generated file from VFS, wrap it as a Blob, and trigger a browser download.
function App() {
const MergeAndSplitTableCell = async () => {
// Get the Spire.Doc WASM module
const wasmModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!wasmModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample Word file into VFS
let inputFileName = "TableSample.docx";
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);
// Load the document
let doc = new wasmModule.Document();
doc.LoadFromFile(inputFileName);
let section = doc.Sections.get_Item(0);
let table = section.Tables.get_Item(0);
// Horizontal merge: merge columns 2 and 3 in row 6
table.ApplyHorizontalMerge(6, 2, 3);
// Vertical merge: merge rows 4 and 5 in column 2
table.ApplyVerticalMerge(2, 4, 5);
// Split cell: split the cell at row 8, column 3 into 2 rows and 2 columns
table.Rows.get_Item(8).Cells.get_Item(3).SplitCell(2, 2);
// Define the output file name
const outputFileName = "MergeAndSplitTableCell_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Merge and Split Table Cells</h1>
<button onClick={MergeAndSplitTableCell}>
Generate
</button>
</div>
);
}
export default App;

Format Merged Cells
After merging cells, you typically need to format the merged area — setting font styles, alignment, and background colors — to improve table readability and visual appeal. The following example demonstrates how to create a product price table, merge the "Product" header cell and the version category cells on the left, and apply custom styling.
function AddTable(section) {
let wasmModule = window.wasmModule.spiredoc;
let table = section.AddTable({ showBorder: true });
table.ResetCells(4, 3);
// Table data
let dt = [["Product", "", "Inventory(kg)"],
["Fruit", "Apples", "150"],
["", "Grapes", "200"],
["", "Lemons", "100"]];
for (let r = 0; r < dt.length; r++) {
let dataRow = table.Rows.get_Item(r);
dataRow.Height = 20;
dataRow.HeightType = wasmModule.TableRowHeightType.Exactly;
for (let i = 0; i < dataRow.Cells.Count; i++) {
dataRow.Cells.get_Item(i).CellFormat.Shading.BackgroundPatternColor = wasmModule.Color.Empty;
}
for (let c = 0; c < dataRow.Cells.Count; c++) {
if (dt[r][c] !== "") {
let range = dataRow.Cells.get_Item(c).AddParagraph().AppendText(dt[r][c]);
range.CharacterFormat.FontName = "Arial";
}
}
}
return table;
}
function App() {
const FormatMergedCells = async () => {
// Get the Spire.Doc WASM module
const wasmModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!wasmModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Create a Word document
let doc = new wasmModule.Document();
let section = doc.AddSection();
// Add a table
let table = AddTable(section);
// Create a custom style
let style = new wasmModule.ParagraphStyle(doc);
style.Name = "Style";
style.CharacterFormat.TextColor = wasmModule.Color.get_DeepSkyBlue();
style.CharacterFormat.Italic = true;
style.CharacterFormat.Bold = true;
style.CharacterFormat.FontSize = 13;
doc.Styles.Add(style);
// Horizontal merge: merge columns 0 and 1 in row 0
table.ApplyHorizontalMerge(0, 0, 1);
// Apply the style
table.Rows.get_Item(0).Cells.get_Item(0).Paragraphs.get_Item(0).ApplyStyle(style.Name);
// Set vertical and horizontal alignment
table.Rows.get_Item(0).Cells.get_Item(0).CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
table.Rows.get_Item(0).Cells.get_Item(0).Paragraphs.get_Item(0).Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
// Vertical merge: merge rows 1, 2, and 3 in column 0
table.ApplyVerticalMerge(0, 1, 3);
// Apply the style
table.Rows.get_Item(1).Cells.get_Item(0).Paragraphs.get_Item(0).ApplyStyle(style.Name);
// Set vertical and horizontal alignment
table.Rows.get_Item(1).Cells.get_Item(0).CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
table.Rows.get_Item(1).Cells.get_Item(0).Paragraphs.get_Item(0).Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Left;
// Set column width
table.Rows.get_Item(1).Cells.get_Item(0).SetCellWidth(20, wasmModule.CellWidthType.Percentage);
// Define the output file name
const outputFileName = "FormatMergedCells_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Format Merged Cells</h1>
<button onClick={FormatMergedCells}>
Generate
</button>
</div>
);
}
export default App;

Check Cell Merge Status
When working with tables created by others or generated by automated processes, you often need to identify which cells have been merged to avoid index-out-of-bounds errors. Spire.Doc provides two properties — CellFormat.VerticalMerge and Cell.GridSpan — to detect cell merge status: VerticalMerge indicates vertical merging, and GridSpan indicates the number of columns a cell spans horizontally.
function App() {
const CellMergeStatus = async () => {
// Get the Spire.Doc WASM module
const wasmModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!wasmModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample file into VFS
let inputFileName = "CellMergeStatus.docx";
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);
// Load the document
let doc = new wasmModule.Document();
doc.LoadFromFile(inputFileName);
// Get the first section and first table
let section = doc.Sections.get_Item(0);
let table = section.Tables.get_Item(0);
// Iterate through all cells to detect merge status
let stringBuidler = [];
for (let i = 0; i < table.Rows.Count; i++) {
let tableRow = table.Rows.get_Item(i);
for (let j = 0; j < tableRow.Cells.Count; j++) {
let tableCell = tableRow.Cells.get_Item(j);
let verticalMerge = tableCell.CellFormat.VerticalMerge;
let horizontalMerge = tableCell.GridSpan;
if (verticalMerge === wasmModule.CellMerge.None && horizontalMerge === 1) {
stringBuidler.push("Row " + i + ", cell " + j + ": ");
stringBuidler.push("This cell isn't merged.\n");
} else {
stringBuidler.push("Row " + i + ", cell " + j + ": ");
stringBuidler.push("This cell is merged.\n");
}
}
stringBuidler.push("\n");
}
// Define the output file name
const outputFileName = "CellMergeStatus_output.txt";
// Write the detection result to a text file
window.dotnetRuntime.Module.FS.writeFile(outputFileName, stringBuidler.join('\n'));
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Check Cell Merge Status</h1>
<button onClick={CellMergeStatus}>
Generate
</button>
</div>
);
}
export default App;

FAQ
How to verify if a cell merge was successful
Cause: Merge operations do not return a status value — you need to read cell properties to confirm.
Solution: Use CellFormat.VerticalMerge to check the vertical merge type (CellMerge.None means not merged), and Cell.GridSpan to check the number of columns spanned horizontally (a value of 1 means not merged):
let verticalMerge = tableCell.CellFormat.VerticalMerge;
let horizontalMerge = tableCell.GridSpan;
if (verticalMerge === wasmModule.CellMerge.None && horizontalMerge === 1) {
// Not merged
} else {
// Merged
}
Content lost after splitting a cell
Cause: When SplitCell splits a cell into multiple sub-cells, the original content remains in the first sub-cell by default.
Solution: Manually iterate through the sub-cells to redistribute content after splitting, or back up the cell text via the Paragraphs collection beforehand:
// Back up the content
let cell = table.Rows.get_Item(row).Cells.get_Item(col);
let text = cell.Paragraphs.get_Item(0).Text;
// Split into 2 rows and 2 columns
cell.SplitCell(2, 2);
// Write the content to the new cell
table.Rows.get_Item(row).Cells.get_Item(col).Paragraphs.get_Item(0).AppendText(text);
Index out of range when merging cells
Cause: ApplyHorizontalMerge(row, startCol, endCol) and ApplyVerticalMerge(col, startRow, endRow) use zero-based indexing. Passing indices that exceed the table's actual row or column count will throw an error.
Solution: Check the table dimensions before merging to ensure the end index does not exceed Rows.Count - 1 and Cells.Count - 1:
if (endCol < table.Rows.get_Item(row).Cells.Count && endRow < table.Rows.Count) {
table.ApplyHorizontalMerge(row, startCol, endCol);
}
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Add or Delete Rows and Columns in Word Table with JavaScript in React
2026-07-06 08:30:30 Written by Amy ZhaoIn real-world document development, table structures often need to be adjusted dynamically — adding rows when report data counts are uncertain, inserting or removing columns when fields change, or deleting redundant data rows with a single click. Spire.Doc for JavaScript leverages WebAssembly to edit Word documents directly in the browser, managing fonts and file resources through a virtual file system (VFS) with no backend server required.
This article covers two core features:
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc is installed and the WebAssembly module is initialized.
Add and Delete Rows
In report generation and data display scenarios, the number of table rows is often dynamic. Spire.Doc provides the Rows.RemoveAt method to delete a specific row, the Rows.Insert method to insert a new row at a specified position, and the AddRow method to append a row at the end of the table. The core workflow has three phases: first, load font files and the target Word document into the WASM virtual file system via FetchFileToVFS; then instantiate a Document, load the file, retrieve the target table, and call row/column manipulation methods; finally, save the document, read the generated file from VFS, wrap it as a Blob, and trigger a browser download.
function App() {
const AddOrDeleteRow = async () => {
// Get the Spire.Doc WASM module
const wasmModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!wasmModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load fonts and the document file into VFS
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Load the sample Word file into VFS
let inputFileName = "TableSample.docx";
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);
// Load the document
let doc = new wasmModule.Document();
doc.LoadFromFile(inputFileName);
let section = doc.Sections.get_Item(0);
let table = section.Tables.get_Item(0);
// Delete row 8
table.Rows.RemoveAt(7);
// Create a new row and insert it at a specified position (after row 2)
let row = new wasmModule.TableRow(doc);
for (let i = 0; i < table.Rows.get_Item(0).Cells.Count; i++) {
let tc = row.AddCell();
let paragraph = tc.AddParagraph();
paragraph.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
paragraph.AppendText("Added");
}
table.Rows.Insert(2, row);
// Append a row at the end of the table
table.AddRow();
// Define the output file name
const outputFileName = "AddOrDeleteRow_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Close();
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add And Delete Rows In Word Table</h1>
<button onClick={AddOrDeleteRow}>
Generate
</button>
</div>
);
}
export default App;
The code above performs three row operations on an existing table: deleting row 8, inserting a new row containing "Added" text after row 2, and appending an empty row at the end of the table.

Add and Remove Columns
In table structure adjustment scenarios, it is often necessary to add new field columns or remove redundant ones. Since Spire.Doc's table column operations are implemented by manipulating cells row by row, custom AddColumn and RemoveColumn helper functions are needed: to add a column, iterate through each row and insert a new blank cell at the specified index; to remove a column, iterate through each row and delete the cell at the specified index.
function AddColumn(table, columnIndex) {
let wasmModule = window.wasmModule.spiredoc;
for (let r = 0; r < table.Rows.Count; r++) {
let addCell = new wasmModule.TableCell(table.Document);
table.Rows.get_Item(r).Cells.Insert(columnIndex, addCell);
}
}
function RemoveColumn(table, columnIndex) {
for (let r = 0; r < table.Rows.Count; r++) {
table.Rows.get_Item(r).Cells.RemoveAt(columnIndex);
}
}
function App() {
const AddOrRemoveColumn = async () => {
// Get the Spire.Doc WASM module
const wasmModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!wasmModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load fonts and the document file into VFS
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Load the sample file into VFS
let inputFileName = "TableSample.docx";
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);
// Load the document
let doc = new wasmModule.Document();
doc.LoadFromFile(inputFileName);
// Get the first section and first table
let section = doc.Sections.get_Item(0);
let table = section.Tables.get_Item(0);
// Insert a blank column before column 0
let columnIndex1 = 0;
AddColumn(table, columnIndex1);
// Delete column 2
let columnIndex2 = 2;
RemoveColumn(table, columnIndex2);
// Define the output file name
const outputFileName = "AddOrRemoveColumn_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Release resources
doc.Close();
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add And Remove Columns In Word Table</h1>
<button onClick={AddOrRemoveColumn}>
Generate
</button>
</div>
);
}
export default App;
The code above inserts a blank column at column index 0 and removes column 2.

FAQ
Table data is garbled after deleting a row
Cause: When the table contains merged cells, deleting a row by index can cause subsequent row indices to shift, breaking the merged cell structure.
Solution: Before deleting, check whether the target row participates in a merge. If the row contains merged cells, unmerge them first before performing the deletion:
// Check the cell's merge state before deleting
let cell = table.Rows.get_Item(rowIndex).Cells.get_Item(0);
let verticalMerge = cell.CellFormat.VerticalMerge;
if (verticalMerge === wasmModule.CellMerge.None) {
table.Rows.RemoveAt(rowIndex);
} else {
console.warn("This row contains merged cells; consider handling the merge state first");
}
Newly added column appears blank in the document
Cause: The AddColumn function only inserts blank TableCell objects without adding paragraphs and text content to the new cells.
Solution: After inserting cells, iterate through the new column and add paragraphs with text:
function AddColumn(table, columnIndex) {
let wasmModule = window.wasmModule.spiredoc;
for (let r = 0; r < table.Rows.Count; r++) {
let addCell = new wasmModule.TableCell(table.Document);
let paragraph = addCell.AddParagraph();
paragraph.AppendText("New Column");
table.Rows.get_Item(r).Cells.Insert(columnIndex, addCell);
}
}
Index out of bounds when deleting a column
Cause: The column index passed exceeds the maximum column count of the current table, or the row column counts are inconsistent.
Solution: Before deleting, get the column count from the first row as a reference and ensure the index is within range:
let maxColIndex = table.Rows.get_Item(0).Cells.Count - 1;
if (columnIndex <= maxColIndex) {
RemoveColumn(table, columnIndex);
}
Get a Free License
If you wish to remove the evaluation message from the resulting document, or to eliminate functional limitations, please contact our sales team to request a 30-day temporary license.
Creating tables in Word documents is one of the most common requirements in daily office development — whether for data reports, product catalogs, or statistical analysis, tables present information clearly in a structured format. Spire.Doc for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage font and file resources — no backend server required.
This article covers three core features:
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc is installed and the WebAssembly module is initialized.
Create a Formatted Data Table
In real-world development, the most common scenario is writing data returned from a backend into a Word document as a table. The core workflow involves three steps: first, load font files into the WASM virtual file system via FetchFileToVFS; then instantiate a Document to create the document, add a table via AddTable, populate it with data, and configure header rows, alignment, and alternating row colors; finally, save the document, read the generated file from VFS, wrap it as a Blob, and trigger a browser download.
function addTable(section) {
let docModule = window.wasmModule.spiredoc;
let header = ["Name", "Capital", "Continent", "Area", "Population"];
let data =
[
["Argentina", "Buenos Aires", "South America", "2777815", "32300003"],
["Bolivia", "La Paz", "South America", "1098575", "7300000"],
["Brazil", "Brasilia", "South America", "8511196", "150400000"],
["Canada", "Ottawa", "North America", "9976147", "26500000"],
["Chile", "Santiago", "South America", "756943", "13200000"],
["Colombia", "Bagota", "South America", "1138907", "33000000"],
["Cuba", "Havana", "North America", "114524", "10600000"],
["Ecuador", "Quito", "South America", "455502", "10600000"],
["El Salvador", "San Salvador", "North America", "20865", "5300000"],
["Guyana", "Georgetown", "South America", "214969", "800000"],
["Jamaica", "Kingston", "North America", "11424", "2500000"],
["Mexico", "Mexico City", "North America", "1967180", "88600000"],
["Nicaragua", "Managua", "North America", "139000", "3900000"],
["Paraguay", "Asuncion", "South America", "406576", "4660000"],
["Peru", "Lima", "South America", "1285215", "21600000"],
["United States of America", "Washington", "North America", "9363130", "249200000"],
["Uruguay", "Montevideo", "South America", "176140", "3002000"],
["Venezuela", "Caracas", "South America", "912047", "19700000"]
];
let table = section.AddTable({ showBorder: true });
table.ResetCells(data.length + 1, header.length);
// Set up the header row
let row = table.Rows.get_Item(0);
row.IsHeader = true;
row.Height = 20;
row.HeightType = docModule.TableRowHeightType.Exactly;
for (let i = 0; i < row.Cells.Count; i++) {
row.Cells.get_Item(i).CellFormat.Shading.BackgroundPatternColor = docModule.Color.get_Gray();
}
for (let i = 0; i < header.length; i++) {
row.Cells.get_Item(i).CellFormat.VerticalAlignment = docModule.VerticalAlignment.Middle;
let p = row.Cells.get_Item(i).AddParagraph();
p.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
let txtRange = p.AppendText(header[i]);
txtRange.CharacterFormat.Bold = true;
}
// Populate data rows with alternating row colors
for (let r = 0; r < data.length; r++) {
let dataRow = table.Rows.get_Item(r + 1);
dataRow.Height = 20;
dataRow.HeightType = docModule.TableRowHeightType.Exactly;
for (let i = 0; i < dataRow.Cells.Count; i++) {
dataRow.Cells.get_Item(i).CellFormat.Shading.BackgroundPatternColor = docModule.Color.Empty();
}
for (let c = 0; c < data[r].length; c++) {
dataRow.Cells.get_Item(c).CellFormat.VerticalAlignment = docModule.VerticalAlignment.Middle;
dataRow.Cells.get_Item(c).AddParagraph().AppendText(data[r][c]);
}
}
// Apply light blue background to even rows
for (let j = 1; j < table.Rows.Count; j++) {
if (j % 2 == 0) {
let row2 = table.Rows.get_Item(j);
for (let f = 0; f < row2.Cells.Count; f++) {
row2.Cells.get_Item(f).CellFormat.Shading.BackgroundPatternColor = docModule.Color.get_LightBlue();
}
}
}
}
function App() {
const CreateTable = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load font files into VFS
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Create a blank document
let doc = new docModule.Document();
let section = doc.AddSection();
// Add the table
addTable(section);
// Define the output file name
const outputFileName = "CreateTable_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Click the button below to create a table in a Word document.</h1>
<button onClick={CreateTable}>
Generate
</button>
</div>
);
}
export default App;
Word output generated from a formatted data table

Create a Table from HTML
In web development, HTML tables are a universal format for displaying data. Spire.Doc provides the AppendHTML method, which can parse an HTML string directly into a Word document table, greatly simplifying the conversion from web content to Word documents. This is particularly useful for scenarios where you need to export table data from a web page to a Word document.
function App() {
const CreateTableFromHTML = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load font files into VFS
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// HTML string
let HTML = "<table border='2px'>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>";
// Create a Word document
let doc = new docModule.Document();
// Add a section
let section = doc.AddSection();
// Add a paragraph and append the HTML string
section.AddParagraph().AppendHTML(HTML);
// Define the output file name
const outputFileName = "CreateTableFromHTML_output.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Click the button below to create a table from HTML in a Word document.</h1>
<button onClick={CreateTableFromHTML}>
Generate
</button>
</div>
);
}
export default App;
Word table created from HTML

Create a Nested Table
A nested table is a table inserted within a cell of another table. This is commonly used for complex document layouts — for example, in a product catalog, the main table displays product names and descriptions, while a sub-table containing specification parameters (number, item, price) is embedded inside the description cell. Spire.Doc makes nested table creation easy with the Cell.AddTable method.
function App() {
const CreateNestedTable = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
// Check if the module is ready
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load font and document files into VFS
await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Create a new document
let doc = new docModule.Document();
let section = doc.AddSection();
// Add main table (2 rows, 2 columns)
let table = section.AddTable({ showBorder: true });
table.ResetCells(1, 2);
// Set column widths
table.Rows.get_Item(0).Cells.get_Item(0).SetCellWidth(70, docModule.CellWidthType.Point);
table.Rows.get_Item(0).Cells.get_Item(1).SetCellWidth(150, docModule.CellWidthType.Point);
table.Rows.get_Item(0).Height=200;
table.AutoFit(docModule.AutoFitBehaviorType.AutoFitToWindow);
// Insert content into cells
table.Rows.get_Item(0).Cells.get_Item(0).AddParagraph().AppendText("Spire.Doc for JavaScript");
let text = "Spire.Doc for JavaScript is a professional Word " +
"JavaScript library designed for developers to quickly and " +
"high-quality create, read, write, convert, and print Word " +
"document files on any JavaScript platform.";
table.Rows.get_Item(0).Cells.get_Item(1).AddParagraph().AppendText(text);
table.Rows.get_Item(0).Cells.get_Item(1).AddParagraph();
// Add a nested table in the cell (first row, second column)
let nestedTable = table.Rows.get_Item(0).Cells.get_Item(1).AddTable({ showBorder: true });
nestedTable.ResetCells(5, 2);
nestedTable.AutoFit(docModule.AutoFitBehaviorType.AutoFitToContents);
// Fill nested table content
nestedTable.Rows.get_Item(0).Cells.get_Item(0).AddParagraph().AppendText("Feature Module");
nestedTable.Rows.get_Item(0).Cells.get_Item(1).AddParagraph().AppendText("Typical Use Cases");
nestedTable.Rows.get_Item(1).Cells.get_Item(0).AddParagraph().AppendText("Document Generation");
nestedTable.Rows.get_Item(2).Cells.get_Item(0).AddParagraph().AppendText("Format Conversion");
nestedTable.Rows.get_Item(3).Cells.get_Item(0).AddParagraph().AppendText("Content Editing");
nestedTable.Rows.get_Item(4).Cells.get_Item(0).AddParagraph().AppendText("Print Service");
nestedTable.Rows.get_Item(1).Cells.get_Item(1).AddParagraph().AppendText("Dynamically generate contracts, invoices, data reports, and mail merge");
nestedTable.Rows.get_Item(2).Cells.get_Item(1).AddParagraph().AppendText("Convert between Word and PDF, HTML, RTF, XML, images, and more");
nestedTable.Rows.get_Item(3).Cells.get_Item(1).AddParagraph().AppendText("Extract text/images, add watermarks, track revisions, and fill forms");
nestedTable.Rows.get_Item(4).Cells.get_Item(1).AddParagraph().AppendText("Background silent printing, custom paper size, and page setup");
// Define the output file name
const outputFileName = "CreateNestedTable_output-en.docx";
// Save the document
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// Release resources
doc.Dispose();
// Read the generated file from VFS and trigger download
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Click the button below to create a nested table in a Word document.</h1>
<button onClick={CreateNestedTable}>
Generate
</button>
</div>
);
}
export default App;
Nested table output in Word

FAQ
The downloaded file cannot be opened or appears corrupted
Cause: The MIME type is incorrect when creating the Blob, so the browser cannot properly identify the file format.
Solution: Use the correct Word document MIME type:
const modifiedFile = new Blob([fileArray], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
Table borders are missing or inconsistent
Cause: When adding a table with AddTable({ showBorder: true }), borders are enabled by default, but tables created directly via the Table constructor need borders set manually.
Solution: When creating a table via the constructor, explicitly set the border type:
let table = new wasmModule.Table(doc, false);
table.Format.Borders.BorderType = wasmModule.BorderStyle.Single;
Get a Free License
If you want to remove the evaluation message from the result document, or eliminate functional limitations, contact our sales team to request a 30-day temporary license.