c# Find and Replace Text in a Word Document

烂漫一生 提交于 2019-12-10 12:23:12

问题


i want to Create and Manipulate Word Documents Programmatically Using DocX ! and create a word template InvoiceTemplate.docx this is my code :

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;
}

but nothing happend to my NewLoadedShipment.docx ! can some one help please !


回答1:


So I usually advocate Using DocXTemplateEngine for this purpose. Simpler than using novacode-docx for template replacement.

Fills in standard mail merge fields in a simple way

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

Available https://www.nuget.org/packages/swxben.docxtemplateengine/




回答2:


There is a function called "ReplaceText" in DocX that allows you to replace text within the document.

You must first reference you template like this for example...

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

Then you can do...

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

Hope this helps!



来源:https://stackoverflow.com/questions/25722196/c-sharp-find-and-replace-text-in-a-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!