Tables 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.
