c# - Powerpoint 到文本 C# - Microsoft.Interop

标签 c# text powerpoint office-interop file-conversion

我一直在尝试阅读最近 3 天的 .ppt 文件。我在互联网上搜索了很多,并提出了不同的源代码片段,但没有什么是完美的。现在我尝试了这段代码,它没有打印“Check4”,因为“Foreach”语句中存在一些未识别的问题,并抛出异常。请指导我。我非常需要它。

public static  void ppt2txt (String source)
        {
            string fileName = System.IO.Path.GetFileNameWithoutExtension(source);
            string filePath = System.IO.Path.GetDirectoryName(source);
            Console.Write("Check1");
            Application pa = new Microsoft.Office.Interop.PowerPoint.ApplicationClass ();
            Microsoft.Office.Interop.PowerPoint.Presentation pp = pa.Presentations.Open (source,
            Microsoft.Office.Core.MsoTriState.msoTrue,
            Microsoft.Office.Core.MsoTriState.msoFalse,
            Microsoft.Office.Core.MsoTriState.msoFalse);
            Console.Write("Check2");
            String pps = "";
            Console.Write("Check3");
            foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides)
            {
            foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
            pps += shape.TextFrame.TextRange.Text.ToString ();
            }

            Console.Write("Check4");

            Console.WriteLine(pps);
        }

抛出的异常是

System.ArgumentException: The specified value is out of range. at Microsoft.Office.Interop.PowerPoint.TextFrame.get_TextRange() at KareneParser.Program.ppt2txt(String source) in c:\Users\Shahmeer\Desktop\New folder (2)\KareneParser\Program.cs:line 323 at KareneParser.Program.Main(String[] args) in c:\Users\Shahmeer\Desktop\New folder (2)\KareneParser\Program.cs:line 150

捕获到异常的第323行

pps += shape.TextFrame.TextRange.Text.ToString ();

提前致谢。

最佳答案

看起来您需要检查形状对象以查看它们是否存在 TextFrame 和 Text。

在嵌套的 foreach 循环中试试这个:

foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides)
{
   foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
   {
        if(shape.HasTextFrame == Microsoft.Office.Core.MsoTriState.msoTrue)
        {
           var textFrame = shape.TextFrame;
           if(textFrame.HasText == Microsoft.Office.Core.MsoTriState.msoTrue)
           {
              var textRange = textFrame.TextRange;
              pps += textRange.Text.ToString ();
           }
        }

   }
}

这当然未经我测试,但在我看来,当您的 foreach 循环时,您正在尝试访问 powerpoint 文档中不存在文本的某些形状,因此超出范围异常。我添加了检查以确保它仅在存在文本时才将文本附加到您的 pps 字符串。

关于c# - Powerpoint 到文本 C# - Microsoft.Interop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434684/

相关文章:

vba - Powerpoint VBA - 均匀分布列

c# - 检索Excel工作表单元格值

python - 从 tkinter 中的文本小部件复制格式化文本

c - 文本到二进制数据库

c# - w3wp.exe(NETWORK SERVICE 用户)正在锁定新创建的文件并阻止访问它

http - 如何从 powerpoint 检测超链接的 HTTP UA

c# - Infragistics UltraGrid 中复选框的检查更改会引发哪个事件?

c# - 如何使用 Restful API (HATEOAS) 提交深度嵌套的资源

c# - 从哈希表中读取 SortedList

javascript - 检测页面元素中选择(突出显示)或单击的内容?