首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c#在Word文档中查找和替换文本

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

Stack Overflow用户
提问于 2014-09-08 10:29:41
回答 2查看 5.7K关注 0票数 0

我希望使用DocX以编程方式创建和操作Word文档!并创建一个word模板InvoiceTemplate.docx --这是我的代码:

代码语言:javascript
复制
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什么都没发生!有人能帮忙吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-08 23:17:06

因此,我通常主张为此目的使用DocXTemplateEngine。比使用novacode docx替换模板更简单。

以简单的方式填充标准邮件合并字段

代码语言:javascript
复制
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/

票数 1
EN

Stack Overflow用户

发布于 2015-01-20 15:20:00

在ReplaceText中有一个名为“DocX”的函数,它允许您替换文档中的文本。

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

代码语言:javascript
复制
DocX letter = DocX.Load(%YOUR TEMPLATE NAME%);

那你就可以..。

代码语言:javascript
复制
letter.ReplaceText("%REPLACE_THIS%","%WITH_THIS%");

希望这能有所帮助!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25722196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档