How can I control table column width in Word documents using DocX?

十年热恋 提交于 2019-12-12 13:53:12

问题


I am trying to recreate a table like this:

I am using the DocX library to manipulate Word files, but I'm having trouble getting the widths right. Trying to set the widths of cells only seems to work when it's not set to the window autofit mode, and it only seems to resize when the specified width is greater than half of the table width, or rather, I can make a cell bigger than half the width but not smaller.

What would be the simplest way to reproduce the intended table?


回答1:


I found the answer to this myself. In order to properly set the width, you have to loop through each cell in a column and set every width. This will not work with any autofit options selected.




回答2:


Try this :

Table table = doc.AddTable(2, 2);
table.SetColumnWidth(0, 500);
//first is column index, the second is column width



回答3:


Bit of an old post to tag to, but after having the same issue it would appear that none of the widths on either the cells or columns actually work, so as a dirty workaround, you can loop through each column and cell adding text to each of the cells, make the text white and finally use the autofit option to autofit to contents eg.

Table t2 = doc.AddTable(2, 8);
for (int i = 0; i < t2.RowCount; i ++)
{
     for(int x = 0; x < t2.ColumnCount; x++)
     {
        t2.Rows[i].Cells[x].Paragraphs.First().Append("12").Color(Color.White);
     }
}
t2.AutoFit = AutoFit.Contents;
doc.InsertTable(t2);



回答4:


This is the way:

Table t = doc.AddTable(1, 5);
t.SetWidthsPercentage(new[] { 20f, 20f, 40f, 10f, 10f }, 500);

The float array sets width percentage for each of the columns, second parameter is the total width of the table.



来源:https://stackoverflow.com/questions/23692439/how-can-i-control-table-column-width-in-word-documents-using-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!