2

I am trying to write and append some text to a word file using c#, however, I am unable to get expected results. Could you please help me out of this ?

Below is my code-

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    
    namespace WFA1
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //FileStream F = new FileStream("testdoc2.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                Console.WriteLine("Sourav");           
                string filename = @"C:\\Desktop\\myfile.docx";
                Console.WriteLine(filename);
                try
                {
                    using (FileStream fs = File.OpenWrite(filename))
                    {
                        Byte[] content = new UTF8Encoding(true).GetBytes("Hello I am learning C#");
                        fs.Write(content, 0, content.Length);
                    }
                }
                catch (Exception Ex)
                {
                    Console.Write(e.ToString());
                }
                
    
    
            }
        }
    }

The above code is a windows form application code behind. I have use FileStream class to write data. However I am facing below issues :-

  1. No file is getting created
  2. Code keeps on running until I stop it manually.

Hence, I tried the below approach too, and I was able to write text to the file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Office.Interop.Word;

namespace WFA1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\testdoc1.docx");
            object missing = System.Reflection.Missing.Value;
            //string s = "Hi";
            //Console.WriteLine(s);               
            doc.Content.Text = textBox1.Text.ToString();
            doc.Save();
            doc.Close(ref missing);

            app.Quit(ref missing);
        }
    }
}

However, still I did not get expected results. below are my issues:-

  1. Unable to append any text. Please let me know how to append using this approach. is there any method we can call to append texts.
  2. Even though I have used Quit method, application is not quitting, until I quit manually.

Also, where can I find the list of methods of class Microsoft.Office.Interop.Word

Please let me know for any other information.

Manoj Kumar
  • 79
  • 1
  • 12
Sourav
  • 496
  • 2
  • 12
  • 28
  • 1
    http://stackoverflow.com/questions/28761877/how-to-insert-text-from-c-sharp-application-into-ms-word-document-and-save-it-as – MethodMan Jul 13 '16 at 16:20
  • or use this to create the document and pay attention to the `ActiveDocument.Save` http://stackoverflow.com/questions/32693480/how-to-insert-text-in-the-end-of-the-document if you don't like those.. then do a simple google search there are plenty more examples out there. – MethodMan Jul 13 '16 at 16:22
  • @MethodMan and upvoter: The accepted solution in that post (your first comment, not second) is entirely incorrect, the poster is overwriting the document and replacing it with a text file, but he gives the text file a `.docx` extension as if it were a word document which it is not. But someone did post a helpful link there at least: [How to: Programmatically Insert Text into Word Documents](https://msdn.microsoft.com/en-us/library/6b9478cs.aspx) – Quantic Jul 13 '16 at 16:34
  • my point in regards to the link is that you can use what was posted then take out and or add onto the code what you need to fit your use case.. – MethodMan Jul 14 '16 at 15:09

3 Answers3

4

Please follow this link https://support.microsoft.com/en-us/kb/316384

Or

You can try this.

Add the following directives:

  • using Microsoft.Office.Interop.Word;

  • using System.Reflection;

For adding Microsoft.Office.Interop.Word;

  • On the Project menu, click Add Reference.
  • On the COM tab, locate Microsoft Word Object Library,and then Select.

(In my case it is Microsoft Word 12.0 Object Library)

Use these codes. I am trying to maintain these codes like your codes -

private void button1_Click(object sender, EventArgs e)
{
   Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();    
   Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"e:\testdoc1.docx");
   object missing = System.Reflection.Missing.Value;                        
   doc.Content.Text += textBox1.Text;
   app.Visible = true;    //Optional
   doc.Save();            
   this.Close();           
}
Kumar Akhil
  • 176
  • 7
1

Here you dynamically create word document and write simple content in it

  private async void btn_WriteIntoWord_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc; 
        try
        {
            object oMissing = System.Reflection.Missing.Value;

            object missing = System.Reflection.Missing.Value;
            lblProcessing.Text = "Writing File.. Please wait";
            int count=0;

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                doc = app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                doc.Content.Font.Size = 12;
                doc.Content.Font.Bold = 1;
                if (count != 0) doc.Content.Text = "Dear Team,";
                int innercount = 0;
                foreach (DataGridViewCell cell in row.Cells)
                {
                    innercount++;

                    if (count != 0)
                    {
                        if (cell.Value != null)
                        {

                            await Task.Delay(1);
                            string value = cell.Value.ToString();
                            switch(innercount)
                            {
                                case 1:
                                     doc.Content.Text += "          EC Name: " + value;
                                    break;
                                case 2:
                                     doc.Content.Text += "          SO#: " + value;
                                    break;
                                case 3:
                                    doc.Content.Text += "           Monthly Hire Rate: " + value.Trim();
                                    break;
                                case 4:
                                    doc.Content.Text += "           Bill amount: " + value.Trim();
                                    break;
                                case 5:
                                    doc.Content.Text += "           Project code: " + value;
                                    break;
                                case 6:
                                    doc.Content.Text += "           Line Text: " + value;
                                    break;
                                case 7:
                                    doc.Content.Text += "           Total WD: " + value;
                                    break;
                                case 8:
                                    doc.Content.Text += "           #NPL: " + value;
                                    break;
                                case 9:
                                    doc.Content.Text += "           Project%: " + value;
                                    break;
                                case 10:
                                    doc.Content.Text += "           Remark: " + value;
                                    break;
                                case 11:
                                    doc.Content.Text += "           ALCON Emp ID: " + value;
                                    break;
                                default:
                                    doc.Content.Text += value;
                                    break;

                            }



                        }

                    }
                }

                if (count != 0)
                {
                    doc.Content.Text += "Thanks,";
                    doc.Content.Text += "NCS team";
                    string filecount = "test" + count.ToString() + ".docx";
                    object filename = @"D:\GenerateEmail\EmailBillingRates\EmailBillingRates\Word\" + filecount;
                    doc.SaveAs2(ref filename);
                    doc.Save();
                    doc.Close();
                }
                if (count == 10)
                    break;
                count++;
            }

            app.Visible = true;    //Optional

            lblProcessing.Text = "";
           // MessageBox.Show("File Saved successfully");
            this.Close();

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            Marshal.ReleaseComObject(app);
        }
    }
}
0

Use Open-XML-SDK (a set of tools to work with Office Word, Excel, and PowerPoint documents) from Microsoft.

The official repo mentioned OfficeIMO (a library that is built on top of OpenXML to work with Word documents).

Here is a sample code for creating docx file using OfficeIMO

var content = "This is a newly created docx document! " +
              $"at {DateTime.Now.ToString(CultureInfo.InvariantCulture)}";
var path = "text.docx";
using var document = WordDocument.Create(path);
var paragraph = document.AddParagraph(content);
document.Save();

No need for other dependencies (like Microsoft.Office.Interop.Word), nor having Office installed at all!

Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28