研发中做了好多关于生成word的功能,但是一直没有时间去整理。导致每一次写功能都在后悔为什么没有整理代码的习惯。哈哈哈。
本文主要功能有根据文档中的域标签(标签或者域的插入方法会在文档结尾处添加)添加相关数据,其次是我一直比较头疼但是一直没有整理,后来通过借鉴一些代码整理成的现在的功能,即生成表格数据。根据word中表格的位置,导出相应的数据,包括合并行数据等。希望对各位同仁比较有帮助。
Document doc = new Document(HttpContext.Current.Server.MapPath("word模板路径.doc"));
string strFolder = HttpContext.Current.Server.MapPath("文件保存路径");
//创建文件夹
if (!Directory.Exists(strFolder))
Directory.CreateDirectory(strFolder);
DocumentBuilder builder = new DocumentBuilder(doc);
1. 根据域导出数据
builder.MoveToMergeField("word中定义的域名");//域名
builder.Write("填充的值");//当前域所要赋的值
2.根据书签导出数据
doc.Range.Bookmarks["word中定义标签名称"].Text = "填充的值";
3.导出表格数据–获取表格对象方法一
//数据行开始的索引 从第二行开始插入数据
int intRowIndex = 1;
//获取表格对象 获取文档中的第一个表格
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
//复制并添加行
table.Rows.Insert(intRowIndex, table.LastRow.Clone(true));
//对表格进行赋值
builder.MoveToCell(0, intRowIndex, 0, 0);
builder.Write("填充数据");
builder.MoveToCell(0, intRowIndex, 1, 0);
builder.Write("填充数据");
//去除最后的空行
if (table != null)
{
table.LastRow.Remove();
}
4.导出表格数据–获取表格对象方法二
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获得word中的所有表格
Table table1 = allTables[1] as Aspose.Words.Tables.Table; //取到第二个表
DocumentBuilder builder = new DocumentBuilder(doc);
int rowsNum = 0; //插入数据开始行
builder.MoveTo(table1.Rows[rowsNum].Cells[0].Paragraphs[0]);
builder.Write(Num.ToString());
builder.MoveTo(table1.Rows[rowsNum].Cells[1].Paragraphs[0]);
builder.Write("值");
5.复杂表格数据导出 包括多行数据导出 以及合并列等
过两天再写。。。