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;
}
}
}
}
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
//Access the first section
Section section = doc.Sections[0];
//Access the first table
Table table = section.Tables[0] as Table;
//Add a new column
AddColumn(table);
//Save the Word file
string output = "output.docx";
doc.SaveToFile(output, FileFormat.Docx2013);
}
private static void AddColumn(Table table)
{
string header = "NewColumn";
string[] data = { "e-iceblue", "e-iceblue", "e-iceblue", "e-iceblue", "e-iceblue", "e-iceblue", "e-iceblue" };
for (int r = 0; r < table.Rows.Count; r++)
{
TableRow row = table.Rows[r];
TableCell addCell = new TableCell(table.Document);
row.Cells.Add( addCell);
if (row.IsHeader)
{
addCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = addCell.AddParagraph();
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange txtRange = p.AppendText(header);
txtRange.CharacterFormat.Bold = true;
}
else
{
for (int d = 0; d < data.Length; d++)
{
if (d + 1 == r)
{
addCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
addCell.AddParagraph().AppendText(data[d]);
}
}
}
}
}