在指定段落下增加表格

发布时间 2023-07-07 22:05:43作者: 人生无常-大肠包小肠

Document document = new Document();
document.LoadFromFile("C:\\Users\\ZYB\\Desktop\\test.docx");
Section section = document.Sections[0]; // 获取第一个节
Paragraph title = null;
foreach (Paragraph paragraph in section.Paragraphs)
{
if (paragraph.Text == "法大师傅士大夫的")
{
title = paragraph;
break;
}
}
int rowCount = 3; // 行数
int columnCount = 4; // 列数

Table table = section.AddTable();
table.ResetCells(rowCount, columnCount);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
TableRow row = table.Rows[rowIndex];
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
TableCell cell = row.Cells[columnIndex];
cell.AddParagraph().AppendText($"行{rowIndex + 1}, 列{columnIndex + 1}");
}
}

// 在指定标题段落后插入表格
section.Body.ChildObjects.Insert(section.Body.ChildObjects.IndexOf(title) + 1, table);

document.SaveToFile("d:/YourDocument.docx", FileFormat.Docx);