Hi,
I can't find an instruction on how to add a column to a table.
I attach my word file just in case you want to make an example.
Thank you,
Quan
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("sample to iceblue.docx");
Section section = doc.Sections[0];
Table table = section.Tables[0] as Table;
//Set the column index
int columnIndex = 4;
if (columnIndex <= table.Rows[0].Cells.Count)
{
//Add a new column
AddColumn(table, columnIndex);
}
else
{
Console.WriteLine("Index is out of range");
}
string output = "out.docx";
doc.SaveToFile(output, FileFormat.Docx2013);
}
public static void AddColumn(Table table, int columnIndex)
{
//Get the total grid span
int gridSpan = 0;
for (int i = 0; i < columnIndex; i++)
{
gridSpan += table.Rows[0].Cells[i].GridSpan;
}
for (int r = 0; r < table.Rows.Count; r++)
{
//Add a new cell
TableCell addCell = new TableCell(table.Document);
int currentGridSpan = 0;
for (int i = 0; i < table.Rows[r].Cells.Count; i++)
{
//Calculate the current total grid span
currentGridSpan += table.Rows[r].Cells[i].GridSpan;
if (currentGridSpan == gridSpan)
{
table.Rows[r].Cells.Insert(i + 1, addCell);
break;
}
if (currentGridSpan > gridSpan)
{
table.Rows[r].Cells.Insert(i, addCell);
break;
}
}
}
}