一、记录目的:需要在Word中的表格中插入一行, 用下面的语句对Word中的表格(Table)插入行的时候,提示“无法访问此集合中单独的行,因为表格有纵向合并的单元格”,说明Word不支持对有合并单元格的表格增删行,下文记载了解决办法。
object iRow = m_Table.Rows[lastrow];
m_Table.Rows.Add(ref iRow);
二、利用模板读写word的步骤如下:
1.创建WordApp。
2.用WordApp打开模板,作为当前Document。
3.开始向Document写入内容。
4.保存当前Document,并释放对象。
5.退出App,并Kill掉进程。
三、实现
Microsoft.Office.Interop.Word._Application app = null;
object templateFile = "C:\\A.doc";
object expFilePath="C:\\B.Doc";
//1.创建WordApp。
app = new Microsoft.Office.Interop.Word.Application();
//2.用WordApp打开模板,作为当前Document。
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(ref templateFile, 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);
//3.开始向Document的表格中插入行。这里不能直接对行增删,研究发现,可通过在某行的某个单元格之前增行。
Microsoft.Office.Interop.Word.Table m_Table = doc.Tables[1];
int lastRowIndex=m_Table.Rows.Count;
//表格最后一行的第一个单元格
object iCell = m_Table.Cell(lastRowIndex, 1);
//在iCell 上方插入一行
m_Table.Rows.Add(ref iCell);
// 4.保存当前Document,并释放对象。
doc.SaveAs(ref expFilePath, 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);
reportClass.releaseObj(doc);
//5.退出App,并Kill掉进程。
app.Quit(ref missing, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
四、如果需要利用模板批量生成Word,为了提高效率,可在循环体外创建WordApp,循环体内打开Document,保存后释放,再再循环体外退出WordApp。
本文介绍如何在C#中解决无法对有合并单元格的Word表格增删行的问题,提供利用模板读写Word的步骤,包括创建WordApp、打开模板、写入内容、保存和释放对象,以及在批量生成Word时提高效率的方法。

1万+

被折叠的 条评论
为什么被折叠?



