转自原文 ,
因为要做一个提取ppt文字的工程,第一次接触Office开发.
以下是源码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PowerPoint = Microsoft.Office.Interop.PowerPoint; using Microsoft.Office.Core; using System.Runtime.InteropServices; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { String fileName = "F://test.ppt"; Program.Parse(fileName); } public static void Parse(String fileName) { try { PowerPoint.Application pa = new PowerPoint.ApplicationClass(); PowerPoint.Presentation pp = pa.Presentations.Open(fileName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse); Console.WriteLine("Open Success"); PowerPoint.TextFrame frame; String text; foreach (PowerPoint.Slide slide in pp.Slides) { foreach (PowerPoint.Shape shape in slide.Shapes) { if (shape.HasTextFrame == Microsoft.Office.Core.MsoTriState.msoTrue) { frame = shape.TextFrame; if (frame.HasText == Microsoft.Office.Core.MsoTriState.msoTrue) { text = frame.TextRange.Text; Console.WriteLine(text); } } } } } catch (Exception e) { Console.WriteLine(e.Message); } } } }
代码倒挺简单,但是添加引用废了我半天的力气。其中,引用中出现以下内容:
(1).net中有Microsoft.Office.Interop.PowerPoint, Office
(2) com中有Microsoft.Office 1x.0 Object library
Microsoft.Office.Interop.PowerPoint肯定是要添加的.
但Office和Microsoft.Office 1x.0 Object library添加谁?
只添加Office足以(如上图中圈出的那个组件)!
实践证明,
(1)如果只添加Microsoft.Office 1x.0 Object library,会出现下面的错误:
错误 1 类型“Microsoft.Office.Core.MsoTriState”在未被引用的程序集中定义。必须添加对程序集“office, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”的引用
(2)如果Office和Microsoft.Office 1x.0 Object library都添加,就会出现下面的错误:
错误 1 类型“Microsoft.Office.Core.MsoTriState”同时存在于“E:/Program Files/Microsoft Visual Studio 9.0/Visual Studio Tools for Office/PIA/Office12/Office.dll”和“C:/Documents and Settings/Administrator/我的文档/Visual Studio 2008/Projects/PPTPaser/ConsoleApplication1/obj/Debug/Interop.Microsoft.Office.Core.dll”中
原因是MsoTriState在两个dll中都出现了。正确做法:只添加Office引用即可