第一次在csdn上寫文章.
因為要做一個提取ppt文字的工程,第一次接觸Office開發.
以下是源碼:
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using PowerPoint = Microsoft.Office.Interop.PowerPoint;<br />using Microsoft.Office.Core;<br />using System.Runtime.InteropServices;<br />namespace ConsoleApplication1<br />{<br /> public class Program<br /> {<br /> public static void Main(string[] args)<br /> {<br /> String fileName = "F://test.ppt";<br /> Program.Parse(fileName);<br /> }<br /> public static void Parse(String fileName)<br /> {<br /> try<br /> {<br /> PowerPoint.Application pa = new PowerPoint.ApplicationClass();</p><p> PowerPoint.Presentation pp = pa.Presentations.Open(fileName,<br /> Microsoft.Office.Core.MsoTriState.msoTrue,<br /> Microsoft.Office.Core.MsoTriState.msoFalse,<br /> Microsoft.Office.Core.MsoTriState.msoFalse);<br /> Console.WriteLine("Open Success");<br /> PowerPoint.TextFrame frame;<br /> String text;<br /> foreach (PowerPoint.Slide slide in pp.Slides)<br /> {<br /> foreach (PowerPoint.Shape shape in slide.Shapes)<br /> {</p><p> if (shape.HasTextFrame == Microsoft.Office.Core.MsoTriState.msoTrue)<br /> {<br /> frame = shape.TextFrame;<br /> if (frame.HasText == Microsoft.Office.Core.MsoTriState.msoTrue)<br /> {</p><p> text = frame.TextRange.Text;<br /> Console.WriteLine(text);<br /> }<br /> }<br /> }<br /> }<br /> }<br /> catch (Exception e)<br /> {<br /> Console.WriteLine(e.Message);<br /> }<br /> }<br /> }<br />}<br />
代碼倒挺簡單,但是添加引用廢了我半天的力氣.
首先是更改office2003的安裝,參見msdn
http://msdn.microsoft.com/zh-cn/library/aa159923(office.11).aspx#EHAA
這樣,你的引用中就會出現以下內容(當然有可能以前就有了,不用更改office2003的安裝)
(1).net中有Microsoft.Office.Interop.PowerPoint, Office
(2)com中有Microsoft.Office 11.0(或12.0) Object library
Microsoft.Office.Interop.PowerPoint肯定是要添加的.
但Office和Microsoft.Office 11.0(或12.0) Object library添加誰?
只添加Office足以!
實踐證明,
(1)如果只添加Microsoft.Office 11.0(或12.0) Object library,會出現下面的錯誤:
錯誤 1 類型“Microsoft.Office.Core.MsoTriState”在未被引用的程式集中定義。必須添加對程式集“office, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”的引用
(2)如果Office和Microsoft.Office 11.0(或12.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引用即可
這個問題耗了我很多時間解決,因此特地寫此文,希望遇到相同問題的程式員能儘快解決之.
關於com組件的和.net組件的添加還不是很清楚,希望大牛們指教.