'How to set table width percentage using office js
I am working on Office JS word addin project. I am creating a table with 4 columns. I want to set width percentage to 30%,30%,20%,20% respectively. How can I set table width percentake like this. Below is a sample code I am using for table creation
function createTable() {
Word.run(function (context) {
var body = context.document.body;
var Table = body.insertTable(2, array.length, Word.InsertLocation.start, [array]);
return context.sync();
})
.catch(errorHandler);
}
Solution 1:[1]
The Word JS API has no capability (yet) for specificying how a table's columns should behave. It just assumes the default, which means the columns will adjust to their content.
So the only solution is to work with the Word Open XML. Simplest would probably be to insert the entire table (at least the basic structures) using the OOXML methods of the Word JS API, rather than trying to change (replace) an existing table.
The column width, when set as a percentage, is controlled in a number of elements that define the table. This link to OfficeOpenXML.com may be useful.
The following Word Open XML, generated using the COM object model and the property Table.Range.WordOpenXML
, illustrates the basic table structures of a table formatted as a percent of the page width (w:tblW
), and cells as a percentage of the table's width (w:tcW
). The table had two columns, set to 20% and 80%. Note that Word will minimally adjust the percentages based on its layout algorithm, so the actual percentage used in always an approximation.
The w:gridCol
settings also reflect these proportions.
Besides the percentages, the w:type
attribute is important. It tells Word how to interpret the width settings: w:type="pct"
specifies "percent".
The values may see quite large, that's because they're a fifths of a percent. So 5000 is 100%.
<w:tbl>
<w:tblPr><w:tblStyle w:val="TableGrid"/>
<w:tblW w:w="5000" w:type="pct"/>
<w:tblLayout w:type="fixed"/>
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
</w:tblPr>
<w:tblGrid><w:gridCol w:w="944"/><w:gridCol w:w="3700"/></w:tblGrid>
<w:tr>
<w:tc><w:tcPr><w:tcW w:w="1016" w:type="pct"/></w:tcPr>
<w:p/>
</w:tc><w:tc><w:tcPr><w:tcW w:w="3984" w:type="pct"/></w:tcPr>
<w:p/>
</w:tc><
/w:tr>
</w:tbl>
Solution 2:[2]
Use autoFitWindow() function under table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cindy Meister |
Solution 2 | arp |