Search code examples
c#ms-wordoffice-interop

Create, insert text and save a Word doc in C#


I've found loads of useful documentation around creating an instance of a word doc, inserting all manner of text and formatting but cannot find anywhere something to save a document that hasnt already been created and opened programmatically.

Essentially I want to create a docx file and fill it with text from a rich text box. Using code Ive found at How to Insert text in the end of the document I am able to achieve this if I first create a document. But despite suggestions of using _document.SaveAs() (which doesnt exist - version diff i guess) or .Save() supposedly prompting with a SaveAs dialogue if the file doesnt already exist, I always get a type mismatch error. So this is the working code if i pre-create the file to use:

OpenFileDialog SDO = new OpenFileDialog();
SDO.ShowDialog();

Microsoft.Office.Interop.Word._Application oWord;
object oMissing = Type.Missing;
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = false;

oWord.Documents.Open(SDO.FileName);

oWord.Selection.TypeText(richTextBox1.Text);
oWord.ActiveDocument.Save();
oWord.Quit();

Now one would assume that removing the lines for the OpenFileDialogue Documents.Open would go some way to saving a new file created in C#, however even with:

Microsoft.Office.Interop.Word._Application oWord;
object oMissing = Type.Missing;
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = false;

SaveFileDialog SD = new SaveFileDialog();

SD.Filter = "Word File |*.docx";
SD.Title = "Save File";
SD.ShowDialog();


oWord.Documents.Save(SD.FileName,WdNewDocumentType.wdNewXMLDocument);

oWord.Selection.TypeText(richTextBox1.Text);
oWord.ActiveDocument.Save();
oWord.Quit();

Other examples ive seen open the document so that you can save it yourself but i need it saving without any human intervention other than choosing a filename.

Any help appreciated, also the option of third party dlls like spire and gem are precluded so not an option :(

If anyone has a simple example of creating and saving a word doc that didnt exist before the program ran id be much obliged.


Solution

  • The Microsoft MSDN documentation has tons of useful guides and examples.

    You are going to want to include:

    using Word = Microsoft.Office.Interop.Word;
    using Microsoft.Office.Tools.Word;
    

    Then declare your application:

    Word.Application app = new Word.Application();
    

    Declare your new document:

    Word.Document doc = app.Documents.Add();
    

    Add text to your documnet

    There are two ways to save these documents:

    Programmatically

    Using a save file dialog box