在Word中,对于已经有了固定的表头的表格,但是不知道表格具体需要多少行时,我们可以根据需要动态的增加,以及单元格 的拆分,合并等操作。以下 是具体的例子代码(对于没有表头的表格,参照于我的另一篇博客):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Word;
using System.Windows;
using C_STP_WPF_Building.entity;
namespace C_STP_WPF_Building
{
public class Report
{
private _Application wordApp = null; //代表当前应用程序
public _Document wordDoc = null;//代表当前的word文档
private Table table = null;//代表word文档中的表格
private Range allRange;
public _Application Application
{
get
{
return wordApp;
}
set
{
wordApp = value;
}
}
public _Document Document
{
get
{
return wordDoc;
}
set
{
wordDoc = value;
}
}
//通过模板打开文档
public void CreateNewDocument(string filePath)
{
try
{
killWinWordProcess();//杀死word进程
wordApp = new Word.Application();
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.Visible = false;
object missing = System.Reflection.Missing.Value;
object templateName = filePath;
wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
table = wordDoc.Tables[15];//文档中的表格,如果是第一个表格Tables[1].
allRange = wordDoc.Range(missing, missing);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
//该类表示向Word表格中的第n个表格中添加num行,然后向数组中的数据写入表格中
//n为表格序号
//num为要插入几行数据
//rp为插入数据的数组
//包括插入表格,表格合并,表格拆分,插入数据
public void AddRow10(int n, int num, ResultParameter[] rp, Carproportion[] cararray, Variabless[] variablessarray)
{
object miss = System.Reflection.Missing.Value;
Word.Table table = wordDoc.Content.Tables[n];//获取第几个表格
int row = variablessarray.Length * cararray.Length;
for (int i &#