本文介绍通过使用spire.doc for .net 来删除word中的ole对象。插入、修改、读取word ole对象,可参考。
测试文档中的ole对象如下:
c#
using spire.doc;
using spire.doc.documents;
using spire.doc.fields;
using system.io;
namespace deleteole_doc
{
class program
{
static void main(string[] args)
{
//实例化一个document对象,加载一个包含ole对象的文档
document doc = new document();
doc.loadfromfile(@"test.docx");
//遍历文档所有section
foreach (section sec in doc.sections)
{
//遍历section下面所有的子元素
foreach (documentobject obj in sec.body.childobjects)
{
if (obj is paragraph)
{
paragraph par = obj as paragraph;
//遍历段落中的对象
for (int i = 0; i < par.childobjects.count;i )
{
documentobject o = par.childobjects[i];
//获取ole对象
if (o.documentobjecttype == documentobjecttype.oleobject)
{
docoleobject ole = o as docoleobject;
string s = ole.objecttype;
if (s == "acroexch.document.11")//"acroexch.document.11"是指pdf对象对应的progid
{
//删除ole对象
obj.childobjects.remove(ole);
}
else if (s == "excel.sheet.12")//"excel.sheet.12"是指 excel03之后的工作表对应的progid
{
//删除ole对象
obj.childobjects.remove(ole);
}
else if (s == "word.document.12") //"word.document.12"是指03之后的word对应的progid
{
//删除ole对象
obj.childobjects.remove(ole);
}
}
}
}
}
}
//保存文档
doc.savetofile("deleteole.docx",fileformat.docx2013);
}
}
}
vb.net
imports spire.doc
imports spire.doc.documents
imports spire.doc.fields
imports system.io
namespace deleteole_doc
class program
private shared sub main(args as string())
'实例化一个document对象,加载一个包含ole对象的文档
dim doc as new document()
doc.loadfromfile("test.docx")
'遍历文档所有section
for each sec as section in doc.sections
'遍历section下面所有的子元素
for each obj as documentobject in sec.body.childobjects
if typeof obj is paragraph then
dim par as paragraph = trycast(obj, paragraph)
'遍历段落中的对象
for i as integer = 0 to par.childobjects.count - 1
dim o as documentobject = par.childobjects(i)
'获取ole对象
if o.documentobjecttype = documentobjecttype.oleobject then
dim ole as docoleobject = trycast(o, docoleobject)
dim s as string = ole.objecttype
if s = "acroexch.document.11" then
'"acroexch.document.11"是指pdf对象对应的progid
'删除ole对象
obj.childobjects.remove(ole)
elseif s = "excel.sheet.12" then
'"excel.sheet.12"是指 excel03之后的工作表对应的progid
'删除ole对象
obj.childobjects.remove(ole)
elseif s = "word.document.12" then
'"word.document.12"是指03之后的word对应的progid
'删除ole对象
obj.childobjects.remove(ole)
end if
end if
next
end if
next
next
'保存文档
doc.savetofile("deleteole.docx", fileformat.docx2013)
end sub
end class
end namespace
ole对象删除结果: