问题
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