2011-11-10 84 views
3

我正在使用Microsoft Office Interop打開Excel文件。該文件放置在工作簿代碼讀取文件的特定文件夾中。現在,要求是Excel文件可以放在任何地方。我相信最好的辦法是將Excel文件作爲嵌入式資源。但是,如果我作爲嵌入式資源附加,我將如何使用Excel工作簿讀取文件。打開Excel工作簿文件使用嵌入式資源

_excelapplication.Workbooks.Open(Filename: pExcelTemplatePath); 

無論文件的位置如何,讀取excel模板文件的最佳方法是什麼?與互操作至少不...

你需要的地方保存爲一個文件 - -

+0

要編輯模板還是僅基於它創建新文檔? – Yahia

+0

只需基於它創建一個新文檔。我將構建操作設置爲「內容」,現在我可以在發佈的文件夾中看到該文件。有關clickonce的 – azamsharp

+0

請參閱http://msdn.microsoft.com/en-us/library/6fehc36e.aspx - 需要進一步幫助嗎? – Yahia

回答

6

你不能直接從嵌入的資源打開它即首先通過從資源閱讀(例如Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceNameOfEmbeddedExcelFile)),然後寫這樣ApplicationData/CommonApplicationData/LocalApplicationData/MyDocuments/CommonDocuments from Environment.SpecialFolder

該流的一些位置的另一種選擇是使用能夠打開庫/從流編輯Excel文件 - 讓我知道,如果你需要一些鏈接庫...

+0

我不介意鏈接到這些庫,我正在研究一種讓人們從流中編輯Office文檔的方法。 – BigBadOwl

+0

@BigBadOwl我認爲你應該發佈一個新的問題......特別是。還有一些額外的上下文,比如:除了能夠從流中打開之外,還需要哪些功能「讓人們從流中編輯Office文檔」?哪些辦公室格式(excel,word,powerpoint ... 2003和/或2010)? – Yahia

0

首先,您應該使用此功能獲取資源文件流:

public static Stream GetResourceFileStream(string fileName) 
      { 
       Assembly currentAssembly = Assembly.GetExecutingAssembly(); 
       // Get all embedded resources 
       string[] arrResources = currentAssembly.GetManifestResourceNames(); 

       foreach (string resourceName in arrResources) 
       { 
        if (resourceName.Contains(fileName)) 
        { 
         return currentAssembly.GetManifestResourceStream(resourceName); 
        } 
       } 

       return null; 
      } 

然後,您可以將流保存到文件:How do I save a stream to a file

並打開它:How to open an Excel file in C#