Aspose.Word 操作word复杂表格 拆分单元格 复制行 插入行 文字颜色
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[0] as Aspose.Words.Tables.Table;//拿到第一个表格
for (int i = 0; i < 5; i++)
{
var roww = table.Rows[2];
//var row = table.LastRow.Clone(true);
var row = roww.Clone(true);//复制第三行(绿色行)
table.Rows.Insert(2 + i, row);//将复制的行插入当前行的上方
}
//var row3=table.Rows[3];
//row3.Cells[0].AppendChild(new Paragraph(doc).AppendChild(new Run(doc, "test"))); //报错
builder.MoveToCell(0,3,0,0); //移动到第一个表格的第四行第一个格子
builder.Write("test"); //单元格填充文字
//不能用此方法 表格会错乱
//var row1 = CreateRow(7, new string[] { "1" }, doc);
//var row2 = CreateRow(12, new string[] { "2" }, doc);
//table.Rows.Insert(3, row1);
//table.Rows.Add(row2);
doc.Save(savePathWord.ToString());
MessageBox.Show("ok");
System.Diagnostics.Process.Start(savePathWord.ToString());
}
Aspose.Words.Tables.Cell CreateCell(string value,Document doc)
{
Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(doc);
c1.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
c1.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
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;
}
修改文字颜色:
builder.MoveToCell(0, index + dindex, 2, 0);
Aspose.Words.Font font = builder.Font;
font.Color = System.Drawing.Color.Red;
builder.Write("testtest");
font.Color = System.Drawing.Color.Black;
版权声明:本文为博主原创文章,未经博主允许不得转载。
作者:xuejianxiyang
出处:http://xuejianxiyang.cnblogs.com
关于作者:Heaven helps those who help themselves.
本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。