2014-11-25 39 views
1

我在C#中使用OPENXML編輯doc文件,並希望將其保存。進行了更改,但該文件無法保存。當我打開文件時,它不顯示任何更改。我用跟隨代碼做了它。問題與節省doc文件

using (WordprocessingDocument doc = WordprocessingDocument.Open(source, true)) 
{ 
    using (StreamReader reader = new StreamReader(doc.MainDocumentPart.GetStream())) 
    { 
     documentText = reader.ReadToEnd(); 
    } 

    Body body = doc.MainDocumentPart.Document.Body; 
    documentText = documentText.Replace("##date##", "02/02/2014"); 
    documentText = documentText.Replace("##saleno##", "2014"); 
    documentText = documentText.Replace("##Email##", "abc"); 
    documentText = documentText.Replace("##PhoneNo##", "9856321404"); 
    doc.MainDocumentPart.Document.Save(); 
    doc.Close(); 
} 

請幫忙。 謝謝。

回答

2

你永遠不會改變,你要更換你與其他字符串變量的文件中讀取一個字符串變量文件本身。 documentText變量不是神奇地連接到文件中的文本。這是基本的C#。

代碼在本tutorial如圖所示。

// To search and replace content in a document part. 
public static void SearchAndReplace(string document) 
{ 
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) 
    { 
     string docText = null; 
     using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) 
     { 
      docText = sr.ReadToEnd(); 
     } 

     Regex regexText = new Regex("Hello world!"); 
     docText = regexText.Replace(docText, "Hi Everyone!"); 

     using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) 
     { 
      sw.Write(docText); 
     } 
    } 
} 

請注意,他們在最後使用流寫入器將事情保存迴文件。

還值得注意的是,雖然這種快速和骯髒的方法經常在簡單的找到&替代情況下,有更復雜的情況下,你實際上需要使用OOXML API。使用OOXML API,您可以將文檔的每個部分作爲元素樹(與HTML非常相似)。您可以添加和刪除項目到文檔。在這一點上,簡單的調用Save就足夠了。要做到這一點,你必須迭代遍歷零件,可能遞歸地修改元素本身。這當然要複雜得多,但它允許重複模板多次。你可以參考這個SO question,瞭解如何用實際OOXML API替換的例子。

+0

是不是好些了嗎? – Stilgar 2014-11-25 09:35:21

+1

是的,在我看來它現在更有用了。不要忘記,鏈接有時可以打破的,如果你只提供一個鏈接,然後回答有危險它可以在未來成爲無用 – musefan 2014-11-25 09:36:39

+0

是的,非常感謝 – 2014-11-25 10:52:53

1

你需要編寫你的documentText字符串(帶有更改)回到文檔中,你可以使用StreamWriter來完成,如下所示:

using (WordprocessingDocument doc = WordprocessingDocument.Open(source, true)) 
{ 
    using (StreamReader reader = new StreamReader(doc.MainDocumentPart.GetStream())) 
    { 
     documentText = reader.ReadToEnd(); 
    } 

    Body body = doc.MainDocumentPart.Document.Body; 
    documentText = documentText.Replace("##date##", "02/02/2014"); 
    documentText = documentText.Replace("##saleno##", "2014"); 
    documentText = documentText.Replace("##Email##", "abc"); 
    documentText = documentText.Replace("##PhoneNo##", "9856321404"); 

    // Write text to document. 
    using (StreamWriter writer = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create))) 
    { 
     writer.Write(documentText); 
    } 
} 
+0

不工作,我試了一下..對不起 – 2014-11-25 10:20:19

+0

@NidhiSavani:也許最後的'Save'位是 – musefan 2014-11-25 11:27:10

+0

的問題。我解決了Stilgar的答案。謝謝。 – 2014-11-26 06:05:23