Word操作类

using System;
using System.Collections.Generic;
using System.Text;
using Word;
using System.Data;
using System.Collections;

namespace Pixysoft.Office
{
    /// <summary>
    /// 支持创建、打开、保存、关闭文档
    /// 支持页面设置
    /// 支持普通文字输入设置
    /// 支持表插入
    /// 支持BookMark
    /// </summary>
    public class WordDocuments
    {
        private bool visible = false;

        private object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
        private object oMissing = System.Reflection.Missing.Value;

        Word._Application oWord;
        Word._Document oDoc;

        Hashtable templTableHash = new Hashtable();

        #region 文件操作
        /// <summary>
        /// 新建一个空文档
        /// </summary>
        public void CreateDocument()
        {
            CloseDocument();
            oWord = new Word.Application();
            oWord.Visible = visible;
            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        }
        /// <summary>
        /// Creates the document with template.
        /// </summary>
        public void CreateDocumentWithTemplate(object path)
        {
            CloseDocument();
            oWord = new Word.Application();
            oWord.Visible = visible;
            oDoc = oWord.Documents.Add(ref path, ref oMissing, ref oMissing, ref oMissing);
            templTableHash.Clear();
            int i = 0;
            foreach (Word.Table table in oDoc.Tables)
            {
                templTableHash.Add(i, table);
                i++;
            }
        }
        /// <summary>
        /// 打开项目
        /// </summary>
        /// <param name="path">The path.</param>
        public void OpenDocument(object path)
        {
            CloseDocument();
            oWord = new Word.Application();
            oWord.Visible = visible;
            oDoc = oWord.Documents.Open(ref path,
            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);
            templTableHash.Clear();
            int i = 0;
            foreach (Word.Table table in oDoc.Tables)
            {
                templTableHash.Add(i, table);
                i++;
            }
        }
        /// <summary>
        /// 保存当前项目
        /// </summary>
        public void SaveDocument()
        {
            if (oWord == null)
                throw new Exception("Create / Open Document first!");
            if (oDoc == null)
                throw new Exception("Create / Open Document first!");
            if (!oDoc.Saved)
                oDoc.Save();
        }
        /// <summary>
        /// 项目另存为
        /// </summary>
        public void SaveAsDocument(object path)
        {
            if (oWord == null)
                throw new Exception("Create / Open Document first!");
            if (oDoc == null)
                throw new Exception("Create / Open Document first!");
            oDoc.SaveAs(ref path, 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);
        }
        /// <summary>
        /// 关闭项目
        /// </summary>
        public void CloseDocument()
        {
            if (oDoc != null)
            {
                try
                {
                    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                    oDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
                }
                catch
                {
                    //Already Close
                }
            }
            if (oWord != null)
            {
                try
                {
                    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                    oWord.Documents.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
                }
                catch
                {
                    //Already Close
                }
            }
        }
        #endregion

        #region 页面设置
        /// <summary>
        /// 设置页方向为衡
        /// </summary>
        /// <param name="oDoc">The o doc.</param>
        /// <param name="value">The value.</param>
        public void SetOrientLandscape()
        {
            if (oDoc != null)
                oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
        }
        /// <summary>
        /// 设置页面为竖
        /// </summary>
        public void SetOrientPortrait()
        {
            if (oDoc != null)
                oDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;
        }
        /// <summary>
        /// 设置页边距
        /// </summary>
        /// <param name="oDoc">The o doc.</param>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <param name="top">The top.</param>
        /// <param name="bottom">The bottom.</param>
        public void Margin(float left, float right, float top, float bottom)
        {
            if (oDoc == null)
                return;
            oDoc.PageSetup.LeftMargin = left;
            oDoc.PageSetup.RightMargin = right;
            oDoc.PageSetup.TopMargin = top;
            oDoc.PageSetup.BottomMargin = bottom;
        }
        /// <summary>
        /// 页大小
        /// </summary>
        public void PageSize()
        {
        }
        #endregion

        #region 追加文字
        /// <summary>
        /// 追加标题1
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineOne(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Times New Roman", 22f, System.Drawing.FontStyle.Bold);
            WordParagraphFormat format = new WordParagraphFormat(17f, 16.5f, 0f, 0f, 2.41f);
            AppendText(text, font, format);
        }
        /// <summary>
        /// 追加标题2
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineTwo(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Arial", 16f, System.Drawing.FontStyle.Bold);
            WordParagraphFormat format = new WordParagraphFormat(13f, 13f, 0f, 0f, 1.73f);
            AppendText(text, font, format);
        }
        /// <summary>
        /// 追加标题3
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineThree(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Times New Roman", 16f, System.Drawing.FontStyle.Bold);
            WordParagraphFormat format = new WordParagraphFormat(13f, 13f, 0f, 0f, 1.73f);
            AppendText(text, font);
        }

        /// <summary>
        /// 追加正文
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendText(string text)
        {
            this.AppendText(text, null, null);
        }
        /// <summary>
        /// Appends the text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="font">The font.</param>
        public void AppendText(string text, System.Drawing.Font font)
        {
            if (font == null)
                font = new System.Drawing.Font("Times New Roman", 10.5f);
            this.AppendText(text, font, null);
        }
        /// <summary>
        /// 在文章后添加段落。使用Word格式
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="font">The font.</param>
        /// <param name="textAlign">The text align.</param>
        public void AppendText(string text, System.Drawing.Font font, WordParagraphFormat format)
        {
            if (oDoc == null)
                return;
            if (font == null)
                font = new System.Drawing.Font("Times New Roman", 10.5f);
            if (format == null)
                format = new WordParagraphFormat();

            Word.Paragraph oPara;

            //Set Text
            oPara = oDoc.Content.Paragraphs.Add(ref oMissing);
            if (text != null && text != "")
                oPara.Range.Text = text;

            //Set Text Format
            oPara.Range.Font.Size = font.Size;
            try { oPara.Range.Font.Name = font.Name; }
            catch { oPara.Range.Font.Name = "Times New Roman"; }
            oPara.Range.Font.Italic = font.Italic ? 1 : 0;
            oPara.Range.Font.Bold = font.Bold ? 1 : 0;

            //Set Paragraph
            oPara.Alignment = getParagraphAlign(format.TextAlign);

            if (!format.SpaceAfterAuto)
                oPara.SpaceAfter = format.SpaceAfter;
            else
                oPara.SpaceAfter = 0f;

            if (!format.SpaceBeforeAuto)
                oPara.SpaceBefore = format.SpaceBefore;
            else
                oPara.SpaceBefore = 0f;

            oPara.LeftIndent = format.LeftIndent;
            oPara.RightIndent = format.RightIndent;
            oPara.FirstLineIndent = format.FirstLineIndent;
            if (format.MultiLineSpace)
            {
                oPara.LineSpacingRule = WdLineSpacing.wdLineSpaceMultiple;
                oPara.LineSpacing = format.LineSpacing;
            }
            else
            {
                oPara.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle;
                //oPara.LineSpacing = 1f;
            }

            oPara.Range.InsertParagraphAfter();


        }
        #endregion

        #region 追加表
        /// <summary>
        /// 追加有一个有数据的表
        /// </summary>
        /// <returns></returns>
        public WordTable AppendTable(DataTable table)
        {
            return null;
        }
        /// <summary>
        /// 追加表
        /// 默认宽度 400f
        /// 对齐方式:左对齐
        /// </summary>
        /// <param name="numRows">The num rows.</param>
        /// <param name="numColumns">The num columns.</param>
        /// <returns></returns>
        public WordTable AppendTable(int numRows, int numColumns)
        {
            return AppendTable(numRows, numColumns, new WordTableFormat());
        }
        /// <summary>
        /// 追加表
        /// 对齐方式:左对齐
        /// </summary>
        /// <param name="numRows">The num rows.</param>
        /// <param name="numColumns">The num columns.</param>
        /// <returns></returns>
        public WordTable AppendTable(int numRows, int numColumns, float width, float height)
        {
            return AppendTable(numRows, numColumns, new WordTableFormat(width, height));
        }
        /// <summary>
        /// 追加表
        /// </summary>
        /// <param name="numRows">The num rows.</param>
        /// <param name="numColumns">The num columns.</param>
        /// <returns></returns>
        public WordTable AppendTable(int numRows, int numColumns, WordTableFormat format)
        {
            if (oDoc == null)
                return null;

            Word.Range oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oDoc.Tables.Add(oRng, numRows, numColumns, ref oMissing, ref oMissing);

            Word.Table _table = oDoc.Tables[oDoc.Tables.Count];
            WordTable table = new WordTable(_table);
            table.Format = format;
            return table;
        }
        #endregion

        #region BookMark操作
        /// <summary>
        /// 取得页面BookMark集合
        /// </summary>
        /// <returns></returns>
        public WordBookMarks GetBookMarks()
        {
            if (oDoc == null)
                return null;
            if (oDoc.Bookmarks.Count == 0)
                return null;
            return new WordBookMarks(oDoc.Bookmarks);
        }
        #endregion

        #region 模板操作
        /// <summary>
        /// 粘贴来自模板的表
        /// 只粘贴模板里面第一个表
        /// </summary>
        /// <returns></returns>
        public WordTable PasteTemplateTable()
        {
            if (oDoc == null)
                return null;
            return PasteTemplateTable(0);
        }
        /// <summary>
        /// 粘贴来自模板的表
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public WordTable PasteTemplateTable(int index)
        {
            if (oDoc == null)
                return null;
            if (index < 0 || index + 1 > templTableHash.Count)
                return null;
            Word.Table table = templTableHash[index] as Word.Table;
            table.Range.Copy();
            Word.Range oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oRng.Paste();
            Word.Table _table = oDoc.Tables[oDoc.Tables.Count];
            return new WordTable(_table);
        }
        /// <summary>
        /// 删除所有模板表
        /// </summary>
        public void DeleteTemplateTable()
        {
            if (oDoc == null)
                return;
            foreach (Word.Table table in templTableHash.Values)
            {
                table.Delete();
            }
            templTableHash.Clear();
        }
        /// <summary>
        /// 删除模板里指定的表
        /// </summary>
        /// <param name="index">The index.</param>
        public void DeleteTemplateTable(int index)
        {
            if (oDoc == null)
                return;
            if (index < 0 || index > templTableHash.Count)
                return;
            Word.Table table = templTableHash[index] as Word.Table;
            table.Delete();
            templTableHash.Remove(index);
        }
        #endregion


        #region 内部方法
        /// <summary>
        /// 取得文字对齐方式
        /// </summary>
        /// <param name="align">The align.</param>
        /// <returns></returns>
        private WdParagraphAlignment getParagraphAlign(System.Drawing.ContentAlignment align)
        {
            switch (align)
            {
                case System.Drawing.ContentAlignment.BottomLeft:
                case System.Drawing.ContentAlignment.MiddleLeft:
                case System.Drawing.ContentAlignment.TopLeft:
                    return WdParagraphAlignment.wdAlignParagraphJustify;
                case System.Drawing.ContentAlignment.BottomCenter:
                case System.Drawing.ContentAlignment.MiddleCenter:
                case System.Drawing.ContentAlignment.TopCenter:
                    return WdParagraphAlignment.wdAlignParagraphCenter;
                case System.Drawing.ContentAlignment.BottomRight:
                case System.Drawing.ContentAlignment.MiddleRight:
                case System.Drawing.ContentAlignment.TopRight:
                    return WdParagraphAlignment.wdAlignParagraphRight;
                default:
                    return WdParagraphAlignment.wdAlignParagraphJustify;
            }
        }
        #endregion

        /// <summary>
        /// 设置文档是否显示
        /// </summary>
        /// <value><c>true</c> if visible; otherwise, <c>false</c>.</value>
        public bool Visible
        {
            set
            {
                visible = value;
                if (oWord != null)
                    oWord.Visible = visible;
            }
            get { return visible; }
        }
    }
}
原文地址:https://www.cnblogs.com/beeone/p/2012694.html