当前位置 博文首页 > 渊渟无迹静涛君的博客:C# Aspose.Word 操作word文档【四】
1.今天介绍下第四种word模板写入数据,如图:
2.上图就是今天的模板,接下来就是填充数据了(此方法通用,比?builder.MoveToCell(0, 14 + i, 1, 0);这类方法好)
? ? ? ? #region 对表格进行修改
? ? ? ? private static Table EditCell(Table table, Document doc, int row, int cell, string value)
? ? ? ? {
? ? ? ? ? ? Aspose.Words.Tables.Cell c = table.Rows[row].Cells[cell];
? ? ? ? ? ? Paragraph p = new Paragraph(doc);
? ? ? ? ? ? p.AppendChild(new Run(doc, value));
? ? ? ? ? ? p.ParagraphFormat.Style.Font.Size = 8; ? ?//设置字体大小
? ? ? ? ? ? p.ParagraphFormat.Style.Font.Name = "宋体"; ? ? ? ? ? //设置字体格式
? ? ? ? ? ? c.FirstParagraph.Remove();
? ? ? ? ? ? c.AppendChild(p);
? ? ? ? ? ? table.Rows[row].Cells[cell].Remove();
? ? ? ? ? ? table.Rows[row].Cells.Insert(cell, c);
? ? ? ? ? ? return table;
? ? ? ? }
? ? ? ? #endregion
3.就是调用2的方法进行填充数据
? ? ? ? ? ? string tempFile = Path.GetFullPath("resource/templete/项目建议书模板.doc").ToString(); ?//这个是word模板路径
? ? ? ? ? ? Document doc = new Document(tempFile);
? ? ? ? ? ? DocumentBuilder builder = new DocumentBuilder(doc);
? ? ? ? ? ? NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取word模板中所有表格table
? ? ? ? ? ? Aspose.Words.Tables.Table table4 = allTables[5] as Aspose.Words.Tables.Table;//拿到第6个表格 ? ? ?? ? ? ? ? ?
? ? ? ? ? ? for (int i = 0; i < dt3.Rows.Count; i++) ? ?dt3为数据源DataTable
? ? ? ? ? ? {
? ? ? ? ? ? ? ? EditCell(table4, doc, 0, 1, "\n" + "设备类型:" + dt3.Rows[i]["SBLeiXing"].ToString() + "\r\n" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"设备名称:" + dt3.Rows[i]["SBMingCheng"].ToString() + "\r\n" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"设备数量:" + dt3.Rows[i]["ShuLiang"].ToString() + "\r\n");
? ? ? ? ? ? ? ? EditCell(table4, doc, 1, 1, dt3.Rows[i]["SBYunXingQK"].ToString());
? ? ? ? ? ? ? ? EditCell(table4, doc, 2, 1, dt3.Rows[i]["SBZTJXPingJiaJG"].ToString());
? ? ? ? ? ? ? ? EditCell(table4, doc, 3, 2, dt3.Rows[i]["AnQuanPingJia"].ToString());
? ? ? ? ? ? ? ? EditCell(table4, doc, 4, 2, dt3.Rows[i]["XiaoNengPingJia"].ToString());
? ? ? ? ? ? ? ? EditCell(table4, doc, 5, 2, dt3.Rows[i]["ZhouQiCBPingJia"].ToString());
? ? ? ? ? ? ?}
? ? ? ? ? ?doc.Save(filePath); //保存路径 ? ? ? filePath你可以写死,比如D:\\
4.填充数据结果图: