我正在使用 Com Interop 处理 .Net Framework 4.0 项目,我必须使用 Word 文档中的文本迭代所有范围。我正在使用以下代码,基于 this和 this文章。虽然在大多数情况下它工作正常,但当您有一组形状或在页眉或页脚中包含形状的 Canvas 时,会出现一些问题。在那些情况下,如果 foreach 循环是组/ Canvas 的形状,我无法找到对它们内部形状的访问。
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 会引发异常:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Word.Shape'.
最佳答案
删除所有 Bin 和 Obj 文件夹。包括 Microsoft.Office.Interop.Word.dll 文件作为项目中的引用,以重新生成互操作相关类。在某处定义 Shape 类,以便运行时访问它:
[GuidAttribute("000209A0-0000-0000-C000-000000000046")]
public interface Shape
关于c# - Word Com 互操作 : Iterating all the ranges of a Word document in c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909515/