You could use interop to start from a .dot/x template like that:
using System;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace EditWordDotSO
{
class Program
{
static void Main(string[] args)
{
var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;
Document doc = null;
try
{
doc = applicationWord.Documents.Add(@"path\to\your\a.dotx");
doc.Activate();
}
catch (COMException ex)
{
Console.Write(ex);
//dispose properly as shown below
}
}
}
}
Note: You need to add a COM reference to Microsoft.Office.Interop.Word
tied to your installed MS Word.
Update: As mentioned by @CindyMeister use
this.Application.Documents.Add(@"C:\Test\SampleTemplate.dotx");
instead of creating a new Document()
. Ref: How to: Programmatically Create New Documents
PS: The finally { ... }
block is intended to close the document and dispose the COM objects properly. Why use finally?
Here is a more involved method to do so inspired by this post:
finally {
doc.Close(null, null, null);
applicationWord.Quit();
if (doc != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
if (applicationWord != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(applicationWord);
doc = null;
applicationWord = null;
GC.Collect(); // final cleanup
}
PPS: It's also possible to add or change the template like that:
doc = applicationWord.Documents.Add();
doc.set_AttachedTemplate(@"C:\Test\SampleTemplate.dotx");
doc.UpdateStyles();