First, the class library is introduced, Microsoft.Office.Interop.Word, and then programmed. The code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace Wordtest
{
public partial class Form1:form
{
Object strFileName;
Object Nothing;
Microsoft.Office.Interop.Word.Application Mywordapp = new Microsoft.Office.Interop.Word.ApplicationClass ();
Document Myworddoc;
string strcontent = "";
public Form1 ()
{
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e)
{
Createword ();
//openword ();
}
private void Createword ()
{
strFileName = System.Windows.Forms.Application.StartupPath + "Test.doc";
if (System.IO.File.Exists ((string) strFileName)
System.IO.File.Delete ((string) strFileName);
Object nothing = System.Reflection.Missing.Value;
Myworddoc = MYWORDAPP.DOCUMENTS.ADD (ref nothing, ref no, ref nothing, ref nothing);
#region writes the data read from the database to the Word file
strcontent = "Hello \n\n\r";
myWordDoc.Paragraphs.Last.Range.Text = strcontent;
strcontent = "This is the test procedure";
myWordDoc.Paragraphs.Last.Range.Text = strcontent;
#endregion
//Save the contents of the WordDoc Document object as a doc document
Myworddoc.saveas (ref strFileName, ref nothing, ref no, ref nothing, ref no, ref nothing, ref nothing, ref Nothin G, ref nothing, ref no, ref nothing, ref no, ref nothing, ref no, ref nothing, ref nothing);
//Close WordDoc Document Object
Myworddoc.close (ref nothing, ref no, ref nothing);
//Close WordApp component Objects
Mywordapp.quit (ref nothing, ref no, ref nothing);
This.richTextBox1.Text = strFileName + "\ r \ n" + "create success";
}
private void Openword ()
{
Fontdialog1.showdialog ();
System.Drawing.Font Font = Fontdialog1.font;
Object filepath = "D:\\asp.docx";
object omissing = System.Reflection.Missing.Value;
Myworddoc = MyWordApp.Documents.Open (ref filepath, ref omissing, ref omissing, ref omissing, ref omissing,
ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing,
ref omissing, ref omissing, ref omissing, ref omissing, ref omissing);
myWordDoc.Content.Font.Size = Font. Size;
myWordDoc.Content.Font.Name = Font. Name;
Myworddoc.save ();
richTextBox1.Text = MyWordDoc.Content.Text;
Myworddoc.close (ref omissing, ref omissing, ref omissing);
Mywordapp.quit (ref omissing, ref omissing, ref omissing);
}
}