//Creates a Word document.
WordDocument document = new WordDocument();
//Adds one section.
IWSection section = document.AddSection();
//Initializes a new instance of the WTable class with the specified WordDocument instance.
IWTable table = section.AddTable();
//Resets the table with the specified number of rows and columns.
table.ResetCells(2, 3);
//Append text in each cells in table.
table[0, 0].AddParagraph().AppendText("First cell First row");
table[0, 1].AddParagraph().AppendText("Second cell First row");
table[0, 2].AddParagraph().AppendText("Third cell First row");
table[1, 0].AddParagraph().AppendText("First cell Second row");
table[1, 1].AddParagraph().AppendText("Second cell Second row");
table[1, 2].AddParagraph().AppendText("Third cell Second row");
//Sets table border line width.
table.TableFormat.Borders.LineWidth = 1;
//Reset the margins.
section.PageSetup.Margins.All = 0;
//Calculate the page client width and exclude the border line width to preserve inside page.
float pageClientWidth = section.PageSetup.ClientWidth - (table.TableFormat.Borders.Left.LineWidth + table.TableFormat.Borders.Right.LineWidth);
//Iterating through each cells and setting up width
//in order to fit the table
foreach (WTableRow row in table.Rows)
{
foreach (WTableCell cell in row.Cells)
{
//Updates the cell width based on the page client area width
cell.Width = pageClientWidth / row.Cells.Count;
}
}
//Saves and closes the document
document.Save("Sample.docx");
document.Close(); |