本文将介绍通过使用控件spire.doc for .net来删除word文档中多余的空白行,使文档排版更为紧凑、美观。
测试文档:
c#
//实例化document类的对象
document doc = new document();
//加载测试文档
doc.loadfromfile("test.docx");
//遍历文档,判定段落中是否包含空白行,删除空白行
foreach (section section in doc.sections)
{
for (int i = 0; i < section.body.childobjects.count; i )
{
if (section.body.childobjects[i].documentobjecttype == documentobjecttype.paragraph)
{
if (string.isnullorempty((section.body.childobjects[i] as paragraph).text.trim()))
{
section.body.childobjects.remove(section.body.childobjects[i]);
i--;
}
}
}
}
//保存文档
string result = "result.docx";
doc.savetofile(result, fileformat.docx2013);
vb.net
'实例化document类的对象
dim doc as document = new document
'加载测试文档
doc.loadfromfile("test.docx")
'遍历文档,判定段落中是否包含空白行,删除空白行
for each section as section in doc.sections
dim i as integer = 0
do while (i < section.body.childobjects.count)
if (section.body.childobjects(i).documentobjecttype = documentobjecttype.paragraph) then
if string.isnullorempty(ctype(section.body.childobjects(i),paragraph).text.trim) then
section.body.childobjects.remove(section.body.childobjects(i))
i = (i - 1)
end if
end if
i = (i 1)
loop
next
'保存文档
dim result as string = "result.docx"
doc.savetofile(result, fileformat.docx2013)
测试结果: