[英]Word Com Interop: Iterating all the ranges of a Word document in c#
我正在使用Com Interop进行.Net Framework 4.0项目,并且必须使用Word文档中的文本来迭代所有范围。 基于本文和本文 ,我正在使用以下代码。 尽管在大多数情况下它可以正常工作,但是当您有一组形状或在页眉或页脚中包含形状的画布时,会出现一些问题。 在那些情况下,如果foreach循环的形状是组/画布,则无法访问其中的形状。
private void IterateRanges()
{
foreach (Range range in _document.StoryRanges)
{
var currentRange = range;
do
{
if (RangeStoryTypeIsHeaderOrFooter(currentRange) &&
CurrentRangeHaveShapeRanges(currentRange))
{
foreach (Shape shape in currentRange.ShapeRange)
{
if (shape.TextFrame.HasText == 0)continue;
var finalRange = shape.TextFrame.TextRange;
DoSomething(finalRange);
}
}
else
{
DoSomething(currentRange);
}
currentRange = currentRange.NextStoryRange;
} while (currentRange != null);
}
}
private bool RangeStoryTypeIsHeaderOrFooter(Range range)
{
return (range.StoryType == WdStoryType.wdEvenPagesHeaderStory ||
range.StoryType == WdStoryType.wdPrimaryHeaderStory ||
range.StoryType == WdStoryType.wdEvenPagesFooterStory ||
range.StoryType == WdStoryType.wdPrimaryFooterStory ||
range.StoryType == WdStoryType.wdFirstPageHeaderStory ||
range.StoryType == WdStoryType.wdFirstPageFooterStory);
}
private bool CurrentRangeHaveShapeRanges(Range range)
{
return range.ShapeRange.Count > 0;
}
我尝试使用CanvasItems
和GroupItems
属性没有成功。 其成员无权访问TextRange
属性。
foreach (dynamic groupShape in shape.GroupItems)
{
var textRange = groupShape.TextFrame.TextRange;
}
同样,将groupShape
显式转换为Shape会引发异常:
无法将类型为“ System .__ ComObject”的COM对象转换为接口类型为“ Microsoft.Office.Interop.Word.Shape”。
删除所有Bin和Obj文件夹。 在项目中包括Microsoft.Office.Interop.Word.dll文件作为参考,以重新生成与interop相关的类。 在某处将Shape类定义如下,以便运行时对其进行访问:
[GuidAttribute("000209A0-0000-0000-C000-000000000046")]
public interface Shape
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.