第一次在csdn上写文章.
因为要做一个提取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); } } } }
代码倒挺简单,但是添加引用废了我半天的力气.
首先是更改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组件的添加还不是很清楚,希望大牛们指教.