第三种方法我也是从网上找到的,借鉴下了,然后自己整理出的!
1、建好word 模板
你没有看错,第三种是只有这样的表头,然后动态生成数据!
2、网上找到的代码:
static 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;
}
static 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;
}
3、调用网上的代码,结合自己代码:
string tempFile = Path.GetFullPath("resource/templete/项目建议书模板.doc").ToString();
Document doc = new Document(tempFile);
DocumentBuilder builder = new DocumentBuilder(doc);
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取word中所有表格table
Aspose.Words.Tables.Table table = allTables[4] as Aspose.Words.Tables.Table;//拿到第5个表格 这里你word中是第几个表格就写第几个表格
for (int i = 0; i < dt3.Rows.Count; i++) //dt3 为数据源
{
var row = CreateRow(13, (new string[] { (dt3.Rows.Count-i).ToString(), dt3.Rows[i]["SBBianHao"].ToString(), dt3.Rows[i]["ZiChanBianHao"].ToString(), dt3.Rows[i]["SBMingCheng"].ToString(),dt3.Rows[i]["SuoShuZhanXian"].ToString()
,dt3.Rows[i]["SBLeiXing"].ToString(),dt3.Rows[i]["DianYaDengJi"].ToString(),dt3.Rows[i]["SBXingHao"].ToString(),dt3.Rows[i]["TouYunRiQi"].ToString(),dt3.Rows[i]["ShuLiang"].ToString(),
dt3.Rows[i]["JiLiangDanWei"].ToString(),dt3.Rows[i]["ChuZhiJianYi"].ToString(),dt3.Rows[i]["BeiZhu"].ToString()}), doc); //创建一行
table.Rows.Insert(1, row); //将此行插入第一行的上方
}
4、效果图: