public void SetColumnWidth(Int32 index, Double width)
{
List<Double> widths = ColumnWidths;
if (widths == null || index > widths.Count - 1)
{
if (Rows.Count == 0) throw new Exception("There is at least one row required to detect the existing columns.");
// use width of last row cells
// may not work for merged cell!
widths = new List<Double>();
foreach (Cell c in Rows[Rows.Count - 1].Cells)
{
widths.Add(c.Width);
}
}
// check if index is matching table columns
if (index > widths.Count - 1) throw new Exception("The index is greather than the available table columns.");
// get the table grid props
XElement grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
// if null; append a new grid below tblPr
if (grid == null)
{
XElement tblPr = GetOrCreate_tblPr();
tblPr.AddAfterSelf(new XElement(XName.Get("tblGrid", DocX.w.NamespaceName)));
grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
}
// remove all existing values
grid?.RemoveAll();
// append new column widths
Int32 i = 0;
foreach (var w in widths)
{
double value = w;
if (i == index) value = width;
var gridCol = new XElement(XName.Get("gridCol", DocX.w.NamespaceName),
new XAttribute(XName.Get("w", DocX.w.NamespaceName), value));
grid?.Add(gridCol);
i += 1;
}
// remove cell widths
foreach (Row r in Rows)
foreach (Cell c in r.Cells)
c.Width = -1;
// set fitting to fixed; this will add/set additional table properties
this.AutoFit = AutoFit.Fixed;
}