2011-11-29 51 views
0

我有一個問題,用C處理dotx模板#

我有一個客戶提供的.dotx文件。它包含許多在Word中的developermode中添加的不同類型的字段。

我想能夠使用這個dotx並填充它的值。

如何在C#代碼中執行此操作?

+0

是否有任何限制你可以使用的東西。例如在將運行您的程序的服務器/客戶端上安裝Office? –

+0

那麼,我可以在服務器/客戶端上安裝office等。但重要的是數據來自數據庫或網絡表單。因此,我需要能夠從代碼中操作dotx以生成完成的文檔。 – Wondermoose

+0

@Bali C,我有,謝謝你指出。 – Wondermoose

回答

3

Microsoft OpemXML SDK允許您使用c#處理docx/dotx文件。您可以從here下載Microsoft OpenXML SDK。

您應該首先創建dotx文件的副本。然後在模板中找到字段/內容掌握者。

這裏是一個小例子(使用了豐富的文本框內容領域一個簡單的Word模板):

// First, create a copy of your template. 
File.Copy(@"c:\temp\mytemplate.dotx", @"c:\temp\test.docx", true); 

using (WordprocessingDocument newdoc = WordprocessingDocument.Open(@"c:\temp\test.docx", true)) 
{ 
    // Change document type (dotx->docx) 
    newdoc.ChangeDocumentType(WordprocessingDocumentType.Document); 

    // Find all structured document tags 
    IEnumerable<SdtContentRun> placeHolders = newdoc.MainDocumentPart.RootElement.Descendants<SdtContentRun>(); 

    foreach (var cp in placeHolders) 
    { 
    var r = cp.Descendants<Run>().FirstOrDefault(); 

    r.RemoveAllChildren(); // Remove children 
    r.AppendChild<Text>(new Text("my text")); // add new content 
    }   
} 

上面的例子是一個非常簡單的例子。你必須適應你的單詞模板結構。

希望,這有助於。

+1

我昨天發現了這個,它與我的atm很好地工作。但我會看看這個,也可能對我更好。謝謝! – Wondermoose