比较全的 C# 操作 Word的代码

时间:2022-03-24 03:23:15

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Web;
using System.Data;
using System.Reflection;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Net;

namespace OfficeOperate
{
    public class WordOperate
    {
        #region 动态生成Word文档并填充数据
        ///
        /// 动态生成Word文档并填充数据 
        ///
        /// 返回自定义信息
        public static string CreateWordFile()
        {
            string message = "";
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using System.web的引用
                if( !Directory.Exists( dir + "\\file" ) )
                {
                    Directory.CreateDirectory( dir + "\\file" );  //创建文件所在目录
                }
                string name = DateTime.Now.ToLongDateString() + ".doc";
                object filename = dir + "\\file" + name;  //文件保存路径
                //创建Word文档
                Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );

                ////添加页眉方法一:
                //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
                //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
                //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "Something here" );//页眉内容

                //添加页眉方法二:
                if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )
                {
                    WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
                }
                WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
                string sHeader = "页眉内容";
                WordApp.Selection.HeaderFooter.LinkToPrevious = false;
                WordApp.Selection.HeaderFooter.Range.Text = sHeader;
                WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;