c#查找和替换Word文档中的文本

时间:2014-09-08 10:29:42

标签: c# asp.net ms-word docx novacode-docx

我想使用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没有任何事情发生!有人可以帮忙!

2 个答案:

答案 0 :(得分:2)

有一个名为" ReplaceText"在DocX中,允许您替换文档中的文本。

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

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

然后你可以......

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

希望这有帮助!

答案 1 :(得分:0)

所以我通常提倡使用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/