Populate a word template using C# in ASP.NET MVC3

老子叫甜甜 提交于 2021-02-07 04:17:08

问题


I read it some post referring to Populate word documents, but I need to populate a word document (Office 2007) using C#. For example i want to have a word document with a label [NAME], use that label in C# to put my value, and do all this in a ASP.NET MVC3 controller. Any idea?


回答1:


You could use the OpenXML SDK provided by Microsoft to manipulate Word documents. And here's a nice article (it's actually the third of a series of 3 articles) with a couple of examples.




回答2:


You can do like this : - Introduce "signets" into your Word document template - Work on a copy of your word template - Modify signets values from c# code and save or print your file.

Be carefull with releasing correctly your word process if you treat several documents in your application :)




回答3:


OP's solution extracted from the question:

The solution i found is this:

static void Main(string[] args)
{
    Console.WriteLine("Starting up Word template updater ...");

    //get path to template and instance output
    string docTemplatePath = @"C:\Users\user\Desktop\Doc Offices XML\earth.docx";
    string docOutputPath = @"C:\Users\user\Desktop\Doc Offices XML\earth_Instance.docx";

    //create copy of template so that we don't overwrite it
    File.Copy(docTemplatePath, docOutputPath);

    Console.WriteLine("Created copy of template ...");

    //stand up object that reads the Word doc package
    using (WordprocessingDocument doc = WordprocessingDocument.Open(docOutputPath, true))
    {
        //create XML string matching custom XML part
        string newXml = "<root>" +
            "<Earth>Outer Space</Earth>" +
            "</root>";

        MainDocumentPart main = doc.MainDocumentPart;
        main.DeleteParts<CustomXmlPart>(main.CustomXmlParts);

        //MainDocumentPart mainPart = doc.AddMainDocumentPart();

        //add and write new XML part
        CustomXmlPart customXml = main.AddCustomXmlPart(CustomXmlPartType.CustomXml);
        using (StreamWriter ts = new StreamWriter(customXml.GetStream()))
        {

            ts.Write(newXml);
        }

        //closing WordprocessingDocument automatically saves the document
    }

    Console.WriteLine("Done");
    Console.ReadLine();
}


来源:https://stackoverflow.com/questions/9431018/populate-a-word-template-using-c-sharp-in-asp-net-mvc3

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