2012-01-18 31 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