rows.insert或rows.add前row必须有单元格cell
private void button3_Click(object sender, EventArgs e)
{
object savePathWord ="row.docx";
File.Copy("rowtemplate.docx", savePathWord.ToString(),true);
Aspose.Words.Document doc = new Aspose.Words.Document(savePathWord.ToString());
Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //拿到所有表格
Aspose.Words.Tables.Table table = allTables[1] as Aspose.Words.Tables.Table; //拿到第二个表格
var row=CreateRow(3,(new string[]{"1","2","3"}),doc); //创建一行
table.Rows.Insert(1,row); //将此行插入第一行的上方
Aspose.Words.Tables.Row r2 = new Aspose.Words.Tables.Row(doc);
Aspose.Words.Tables.Cell c21 = new Aspose.Words.Tables.Cell(doc);
Aspose.Words.Tables.Cell c22 = new Aspose.Words.Tables.Cell(doc);
Aspose.Words.Tables.Cell c23 = new Aspose.Words.Tables.Cell(doc);
Aspose.Words.Paragraph p = new Paragraph(doc);
p.AppendChild(new Run(doc, "测试"));
c21.AppendChild(p);
r2.Cells.Add(c21);
r2.Cells.Add(c22);
r2.Cells.Add(c23);
table.Rows.Add(r2); //添加一行
doc.Save(savePathWord.ToString());
MessageBox.Show("ok");
}
Aspose.Words.Tables.Cell CreateCell(string value,Document doc)
{
Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(doc);
Aspose.Words.Paragraph p = new Paragraph(doc);
p.AppendChild(new Run(doc,value));
c1.AppendChild(p);
return c1;
}
Aspose.Words.Tables.Row CreateRow(int columnCount,string[] columnValues,Document doc)
{
Aspose.Words.Tables.Row r2 = new Aspose.Words.Tables.Row(doc);
for (int i = 0; i < columnCount; i++)
{
if (columnValues.Length >i)
{
var cell = CreateCell(columnValues[i], doc);
r2.Cells.Add(cell);
}
else
{
var cell = CreateCell("", doc);
r2.Cells.Add(cell);
}
}
return r2;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。