• C#如何使用Microsoft.Office.Interop.Word操作word文档
  • 发布于 2个月前
  • 362 热度
    0 评论
一.准备工作
首先在工厂中,引用【Microsoft.Office.Interop.Word】,本地安装了world,就能找到这个类库,如下图。Form1系统自动生成的

Form1的界面很简单,就一个按钮

 二 4个完整实例

4个实例,自测过的,都可用,适用很多种情况操作world。

完整代码如下:

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 MSWord = Microsoft.Office.Interop.Word;

namespace _24_word_and_excel_Operator
{
    public partial class Form1 : Form
    {
        object oMissing = System.Reflection.Missing.Value;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //例子1:新建一个word文档,填入自定义的内容
            Example1();

            //例子2:操作模板的例子
            Example2();

            //例子3:操作模板的例子,是例子2的一个简单版本
            Example3();

            //例子4:复杂的例子,操作模板,标签内填值,文档中画表格,表格中填值。文档中填
            Example4(@"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx");
        }
        /// <summary>
        /// 新建一个word文档,填入自定义的内容
        /// </summary>
        private void Example1()
        {
            //创建一个新的Word应用程序对象
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            //创建一个新的Word文档对象,就是创建一个空白的文档
            MSWord.Document doc = wordApp.Documents.Add();
            // 在新文档中添加内容
            MSWord.Paragraph paragraph = doc.Paragraphs.Add();
            paragraph.Range.Text = "Hello, World! This is a sample Word document.";

            // 保存文档,注意:filePath路径要带上文件名
            string filePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\test.docx";
            doc.SaveAs(filePath);

            // 关闭Word应用程序
            wordApp.Quit();
        }

        /// <summary>
        /// 操作模板的例子
        /// </summary>
        private void Example2()
        {
            // 模板文件路径
            string templatePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx";
            // 生成的文档保存路径
            string newDocumentPath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\例子2文档.docx";

            // 创建Word应用程序对象
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            // 打开模板文档
            Microsoft.Office.Interop.Word.Document templateDocument = wordApp.Documents.Open(templatePath);

            // 复制模板文档的内容
            templateDocument.Content.Copy();

            // 创建一个新的空白文档
            Microsoft.Office.Interop.Word.Document newDocument = wordApp.Documents.Add();

            // 将复制的内容粘贴到新文档中
            newDocument.Content.Paste();

            // 修改新文档的内容
            MSWord.Paragraph paragraph = newDocument.Content.Paragraphs.Add();
            paragraph.Range.Text = "This is a document generated from a template.";

            // 保存新文档
            newDocument.SaveAs(newDocumentPath);

            // 关闭模板文档
            templateDocument.Close();

            // 关闭Word应用程序
            wordApp.Quit();
        }
        /// <summary>
        /// 操作模板的例子,是例子2的一个简单版本
        /// </summary>
        /// <param name="templatePath"></param>
        /// <param name="outputPath"></param>
        public void Example3()
        {
            string templatePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx";
            string outputPath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\例子3的文档.docx";

            // 创建Word应用程序对象
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            // 打开模板文档
            MSWord.Document wordDoc = wordApp.Documents.Open(templatePath);
            {
                //这里就是要干什么事了,替换文字,添加内容等操作
                // 替换模板中的文本
                FindAndReplace(wordDoc, "要替换的文字", "替换后的文字");
                // 修改新文档的内容
                MSWord.Paragraph paragraph = wordDoc.Content.Paragraphs.Add();
                paragraph.Range.Text = "This is a document generated from a template.";
            }

            // 保存为新文档
            wordDoc.SaveAs2(outputPath);
            // 关闭Word应用程序对象
            wordApp.Quit();
        }

        private void FindAndReplace(MSWord.Document doc, string findText, string replaceText)
        {
            // 将模板设为可编辑
            doc.Activate();

            // 执行查找和替换操作
            // 可以使用其他查找和替换方法,例如使用Range对象
            object findObj = findText;
            object replaceObj = replaceText;
            object missingObj = Type.Missing;
            doc.Content.Find.Execute(ref findObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
                ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref replaceObj, ref missingObj,
                ref missingObj, ref missingObj, ref missingObj, ref missingObj);
        }
        private void Example4(string strPath)
        {
            object oTemplate = strPath;
            MSWord.Application wordApp = new MSWord.Application();// 创建一个新的Word应用程序对象
            wordApp.Visible = true;
            MSWord.Document oDoc = wordApp.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);// 创建一个新的Word文档对象

            //填写标签
            object[] bookMark = new object[3];
            bookMark[0] = "Test1";
            bookMark[1] = "Test2";
            oDoc.Bookmarks.get_Item(ref bookMark[0]).Range.Text = "第1个标签";
            oDoc.Bookmarks.get_Item(ref bookMark[1]).Range.Text = "第2个标签";


            //定义一个Word中的表格对象
            oDoc.Paragraphs.Last.Range.Text = "直接接入式(正向电能)";
            //用于在Word文档中进行特定的文本插入和调整操作
            object unite = MSWord.WdUnits.wdStory;//这表示将选择操作的范围设为整个文档
            oDoc.Content.InsertAfter("\n");//在文档的内容后面插入一个换行符("\n"),即实现在文档末尾添加一个空行
            wordApp.Selection.EndKey(ref unite, ref oMissing);//将选择操作的焦点移动到文档的结尾,即将光标定位在文档的最后一行。
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;//将光标所在处的段落对齐方式设置为左对齐。
            object WdLine2 = MSWord.WdUnits.wdLine;//换一行;这表示将选择操作的单位设为行。
            wordApp.Selection.MoveDown(ref WdLine2, 6, ref oMissing);//将当前选择向下移动6行。

            int iRow = 5;
            int iColumn = 3;
            MSWord.Table table = oDoc.Tables.Add(wordApp.Selection.Range, iRow, iColumn, ref oMissing, ref oMissing);
            table.Borders.Enable = 1;
            for (int i = 1; i < iRow + 1; i++)
            {
                if (i == 1)
                {
                    table.Cell(i, 1).Range.Text = "电压(V)";
                    table.Cell(i, 2).Range.Text = "电流(A)";
                    table.Cell(i, 3).Range.Text = "电能误差(%)";
                }
                else
                {
                    table.Cell(i, 1).Range.Text = (i + 1).ToString();
                    table.Cell(i, 2).Range.Text = (i + 2).ToString();
                    table.Cell(i, 3).Range.Text = (i + 3).ToString();
                }
            }
            //该行代码的作用是将表格中所有段落的对齐方式设置为居中对齐
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;

            //文档最后填写文字
            oDoc.Paragraphs.Last.Range.Text = "文档最后的位置:\n\r";

            string docname = string.Empty;
            docname = $"文档名称";

            //弹出保存文件对话框,保存生成的Word
            SaveFileDialog sfd = new SaveFileDialog
            {
                Filter = "Word Document(*.docx)|*.docx",
                DefaultExt = "Word Document(*.docx)|*.docx",
                FileName = docname
            };
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                object filename = sfd.FileName;
                oDoc.SaveAs(ref filename, 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);
                // 堆代码 duidaima.com
                // 关闭Word应用程序对象
                wordApp.Quit();
            }
        }
    }
}
三 代码分析解读 (重点部分)
 例子1:适用的情况是,代码创建一个新的world文档的情况

注意:无论是例子1,例子2,例子3,其中的路径,要填写自己本地的路径。

例子2和例子3:
两个例子都是操作world模板的,例子2代码复杂写,例子3精简写。效果都是一样的。例子3中,SaveAs2 方法是 SaveAs 方法的扩展版本,支持更多的保存选项和参数。例子3中, wordDoc.SaveAs2(outputPath);中 outputPath是指定要保存文档的完整路径,包括文件名和文件扩展名。效果如下图

例子4:这个例子稍微复杂一下,设计文档中先插入好标签,标签地方填值,文档中画出表格,表格中填值,文档最后追加文档等操作。
模板文档的标签如下图:

例子4的效果如下图:

用户评论