簡體   English   中英

c#查找和替換Word文檔中的文本

[英]c# Find and Replace Text in a Word Document

我想使用DocX以編程方式創建和處理Word文檔! 並創建一個單詞模板InvoiceTemplate.docx這是我的代碼:

protected void CreateDoc_Click(object sender, EventArgs e)
{
    //Createa docx File
    DocX gDocument;
    gDocument = 
        DocX.Load(@Server.MapPath("InvoiceTemplate.docx"));
    gDocument = 
        CreateInvoiceFromTemplate(DocX.Load(@Server.MapPath("InvoiceTemplate.docx")));
    gDocument.SaveAs(@Server.MapPath("~/DocX/NewLoadedShipment.docx"));
}

private static DocX CreateInvoiceFromTemplate(DocX template)
{
    template.AddCustomProperty(
        new CustomProperty("{rechnung}", "5"));
    template.AddCustomProperty(
        new CustomProperty("{name}", "Maziar"));
    template.AddCustomProperty(
        new CustomProperty("{date}", DateTime.Now.ToString("dd.MM.yyyy")));
    template.AddCustomProperty(
        new CustomProperty("{address}", "12345hamburg"));
    template.AddCustomProperty(
        new CustomProperty("{tell}", "2234543"));
    template.AddCustomProperty(
        new CustomProperty("{amount}", "1000"));
    template.AddCustomProperty(
        new CustomProperty("{rest}", "500"));
    template.AddCustomProperty(
        new CustomProperty("{tax}", "100"));
    template.AddCustomProperty(
        new CustomProperty("{total}", "600"));
    return template;
}

但是我的NewLoadedShipment.docx沒有任何NewLoadedShipment.docx 可以幫忙一下嗎!

DocX中有一個稱為“ ReplaceText”的函數,可讓您替換文檔中的文本。

例如,您必須首先引用您的模板,例如...

DocX letter = DocX.Load(%YOUR TEMPLATE NAME%);

那你就可以...

letter.ReplaceText("%REPLACE_THIS%","%WITH_THIS%");

希望這可以幫助!

因此,我通常主張為此目的使用DocXTemplateEngine。 比使用novacode-docx替換模板更簡單。

用簡單的方法填寫標准郵件合並字段

var templateEngine = new swxben.docxtemplateengine.DocXTemplateEngine();
templateEngine.Process(
    source = "template.docx",
    destination = "dest.docx",
    data = new {
       Name = "SWXBEN"
    }
); 

可用的https://www.nuget.org/packages/swxben.docxtemplateengine/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM