2012-01-18 28 views
0

我一直在过去的一个小时内一直在努力。如何将文档实例转换为FileStream

有人可以帮我将Microsoft.Office.Interop.Word.Document的一个实例转换为FileStream吗?我有这个功能,下面不工作,但可能会帮助你们有什么即时试图做一个想法:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 
using Microsoft.Office.Interop.Word; 
using System.IO; 

namespace DropDownTemplate.Web.WebServices.Word 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "WordGenerator" in code, svc and config file together. 
    public class WordGenerator : IDocumentGenerator 
    { 
     FileStream IDocumentGenerator.GenerateDocument() 
     { 
      // For optional parameters create a missing object 
      object missing = System.Reflection.Missing.Value; 
      // open the document specified in the fileName variable 
      Document adoc = new Document(); 
      adoc.InlineShapes.AddPicture(@"http://localhost:2014/Resources/MG.PNG", ref missing, ref missing, ref missing); 
      using (StreamReader y = new StreamReader()) 
      { 
       y.Read(adoc); 
      } 
      return adoc; 
     } 
    } 
} 
+0

不确定要明白你想要做什么。你有一个文件,你想要它的内容在二进制文件? – 2012-01-18 09:02:22

+0

对不起,这里的代码伙计只是一个新手:(...我想创建一个Word文档,并以FileStream格式发送回Web服务.... – 2012-01-18 09:03:37

+0

从来没有这样做,但可能的解决方案是:1。生成文档2.保存到临时文件3.返回临时文件的内容我不确定你可以直接返回一个FileStream,除非你设置你的服务使用流媒体 – 2012-01-18 09:09:01

回答

1

像这样的东西应该工作:

public class WordGenerator : IDocumentGenerator 
{ 
     FileStream IDocumentGenerator.GenerateDocument() 
     { 
       object missing = System.Reflection.Missing.Value; 
       Document adoc = new Document(); 
       adoc.InlineShapes.AddPicture(@"http://localhost:2014/Resources/MG.PNG", ref missing, ref missing, ref missing); 

       // save the doc file 
       object fileName = Path.GetTempFileName(); 
       adoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); 

       // quit word and release COM objects 
       object saveChanges = WdSaveOptions.wdDoNotSaveChanges; 
       adoc.Application.Quit(ref saveChanges, ref missing, ref missing); 
       Marshal.ReleaseComObject(adoc); 

       // return the stream 
       return new FileStream((string)fileName, FileMode.Open); 

     } 
} 

,你就会有某个时候删除临时文件在未来。

+0

嗨,这是否也可以PDF格式? – 2012-01-19 00:15:53

+1

@AllanChua - 如果您有Office 2010,那么只需将WdSaveFormat.wdFormatPDF作为FileFormat参数传递给SaveAs即可。 – 2012-01-19 08:05:44

1

您缪斯文档保存到文件系统,然后读取到MemoryStream。我不认为序列化会是一个选项,因为Document类可能不是Serializable。

+0

感谢您的回答:) – 2012-01-19 02:05:23