C#操作Word书签模板

C#操作Word书签模板

一制作模板
 
1 新建一个文档,设置文档内容。对于循环的部分,建议放到表格内,这样容易定位、选择、复制、粘贴。
2 将鼠标定位到要插入书签的位置,从菜单上,“插入”->“书签”,弹出对话框,输入书签名,点击“添加”按钮。
 C#操作Word书签模板

 

插入以下书签:order_num,报告日期_,报表模板__,name,age,结论__
 其中,报表模板__,用于定位模板表格。可有可无,没有时,默认表格1。


完成后,所有书签的名称和位置如下图所示:

C#操作Word书签模板


3 保存模板,比如“word书签模板.doc”


二 添加引用

1 右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2 对于WindowsForm方式时,在“添加引用”-->“COM”-->“Microsoft Word 11.0 Object Library”,点击“确定”
C#操作Word书签模板

 

3 对于WebSite网站方式时,打开“添加引用”-->“浏览”项-->”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”
 
注意:此处要查找的“Microsoft.Office.Interop.Word.dll”版本必须为“11.*.*.*”,“*”代表数字
以上版本对应是 Office Word 2003版本。

 

三 编译执行
  如果编译时产生错误 CS1752: 无法嵌入互操作类型“Microsoft.Office.Interop.Word.ApplicationClass”。请改用适用的接口。
,那么,点击 “解决方案”下“工程名称”之下的“引用”之下的Word,在其属性下,将“潜入互操作类型”,由true 改为false即可。

C#操作Word书签模板

 

 

  运行结过如下:


C#操作Word书签模板

 

四 主要的代码如下:

1 首先引用(WindowsForm):Microsoft Word 11.0 Object Library
  或者引用(WebSite):Microsoft.Office.Interop.Word.dll
2 在使用的程序中,加入以下语句
using Word = Microsoft.Office.Interop.Word;

 

===== 1 主操作界面代码 ===

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using word_namespace;
namespace winFormApp_word_bookmark
{
    public partial class Form1 : Form
    {
        private object missing = System.Reflection.Missing.Value;
        WordHelper wdHelp;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            wdHelp = new WordHelper();
            wdHelp.CreateOneDocument("c:\\ii.doc", missing, missing, missing);
            
            //1 这里简单生成样例数据表,工作中要以实际的数据集为准
            DataTable dt = new DataTable();
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("age", typeof(int));

            DataRow dr = dt.NewRow();
            dr["name"] = "张三"; dr["age"] = 20;
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["name"] = "李四"; dr["age"] = 25;
            dt.Rows.Add(dr);

            //2 调用模板替换函数,生成实际的数据
            SetNameCellValue(dt);

 
            wdHelp.SaveAs("c:\\bb.doc");
            wdHelp.Close();

            MessageBox.Show("ok");
        }

        public void SetNameCellValue(DataTable dt)
        {
 
            //(一) 这里设置表头的项目,比如报表日期
            //特别注意:为了容易起见,命名单元格的规则如下,注意:word中书签不能以下划线开头,可能是保留的书签使用
            //1.1 开头处的命名单元格,以1个下划线结尾,比如,报告日期_
            //1.2 中间循环命名单元格,就是正常的,与数据集的字段名一致为好
            //1.3 结尾处的命名单元格,以2个下划线结尾,比如,合计__
            try
            {//为了程序自动处理方便起见
                wdHelp.GoToBookMark("报告日期_");//开始处的命名单元格,都以1个下划线_结尾
                wdHelp.InsertText(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));

            }
            catch (System.Exception ex)
            {

            }

            //(二) 根据数据源的个数,设置重复变化的数据行组,
            //1 声明与命名单元格相关的变量和数组
            int min_Row = 65536, min_Col = 65536, max_Row = 0;
            string min_Name = "";
            int nameCellCount = wdHelp.wordDoc.Bookmarks.Count;//获得命名单元格的总数
            int[] nameCellRow = new int[nameCellCount];//某个命名单元格的行
            int[] nameCellColumn = new int[nameCellCount];//某个命名单元格的列
            string[] nameCellTag = new string[nameCellCount];//某个命名单元格的常规地址 ,比如 $A$1
            string[] nameCellName = new string[nameCellCount];//某个命名单元格的自定义名称,比如 工资

            string strName, str;
            int row1, row2;//选择重复的行
            int nameCellIdx = 0;
            Word.Range tmpRange,srcRange,desRange;

            //2 寻找所有命名的单元格,并找到行号最小者,以便在它之前插入循环行
            for (int k = 0; k < nameCellCount; k++)
            {
                strName = wdHelp.wordDoc.Bookmarks[k + 1].Name;//
                str = strName.Substring(strName.Length - 1, 1);
                if (str == "_")
                {
                    continue;//如果第一个字符为下划线,则认为是固定命名单元格,不是命名的循环单元格
                }
                try
                {
                    tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(strName).Range;

                    nameCellColumn[nameCellIdx] = tmpRange.Cells[1].ColumnIndex;// app.ActiveCell.Column;
                    nameCellRow[nameCellIdx] = tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
                    nameCellName[nameCellIdx] = strName;

                    nameCellTag[nameCellIdx] = "";// app.ActiveCell.Address;//$A$1
                    nameCellTag[nameCellIdx] = "";// nameCellTag[nameCellIdx].Split('$')[1];//$A$1--> A

                    if (min_Row > nameCellRow[nameCellIdx])
                    {
                        min_Row = nameCellRow[nameCellIdx];//最小的行号
                        min_Col = nameCellColumn[nameCellIdx];
                        min_Name = nameCellName[nameCellIdx];

                    }
                    if (max_Row < nameCellRow[nameCellIdx]) max_Row = nameCellRow[nameCellIdx]; ;//最大行号
                    nameCellIdx++;//真实的循环的命名单元格序号
                }
                catch (System.Exception ex)
                {

                }

            }
            nameCellCount = nameCellIdx;//实际要处理的循环的命名单元格数目
            int loopRow = max_Row - min_Row + 1;//一次循环的函数
            //3 也可以使用 //foreach ( Word.Bookmark bk in wh.wordDoc.Bookmarks)MessageBox.Show(bk.Name);
            Word.Table operTable;
            // 方法1 通常使用第一个表来作为模板表
            operTable = wdHelp.wordDoc.Tables[1];
            // 方法2 使用一个书签来标志模板表
            try
            {//使用一个特殊的标签 table_bookmark_template_
                tmpRange = wdHelp.wordDoc.Bookmarks.get_Item("报表模板__").Range;//
                operTable = tmpRange.Tables[1];//得到该书签所在的表,以它为报表的循环模板
            }
            catch (System.Exception ex)
            {

            }
 
            //
            int template_start = 0;
            int template_end = 0;
            int table_columns=operTable.Columns.Count;//本表格的烈数

            tmpRange  = operTable.Cell(min_Row, 1).Range;
            template_start =tmpRange.Start;//循环行组的第一行,第一个单元格,到文档开头的距离
            tmpRange = operTable.Cell(max_Row, table_columns).Range;
            template_end = tmpRange.Start; //循环行组的最后行,最后一个单元格,到文档开头的距离

            srcRange = operTable.Cell(1, 1).Range;
            desRange = operTable.Cell(1, 1).Range;

            //4 根据数据集的实际数据行数,查找命名单元格,循环插入数据
            int cur_row = min_Row;//0;// min_Row;//
            for (int dt_row_idx = 0; dt_row_idx
            {//循环实际的数据行数

//goto xx1;//跳过方法1
                 //方法1 整体多行组,复制和粘贴,看起来复杂
                //4.1 找到行号最小的循环行组的命名单元格,以它来定位
                tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//app.Goto(min_Name);
                //4.2 //插入循环重复的摸板行组的行,使得所有命名单元格都向后移,以便下次循环查找定位使用
               // for (int j = 0; j < loopRow; j++)
               // {//插入需要重复循环的行数loopRow的空行
               //     app.ActiveCell.EntireRow.Insert();
               // }

                //4.3 定位到摸板行组首行
                tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//转到摸板行组的行号最小的命名单元格,以它来定位
                row1 = tmpRange.Cells[1].RowIndex;//a  //摸板行组的第一行
                row2 = row1 + loopRow - 1; //摸板行组的最后一行

                template_start = operTable.Cell(row1, 1).Range.Start;
                //template_end = operTable.Cell(row2, table_columns).Range.Start;//这样少一列
                template_end = operTable.Cell(row2+1, 1).Range.Start;//到下一行,第一个单元格

                //4.4 复制整体模板的多行组,固定的摸板的格式和相关的文字说明,也可一个一个单元格复制
                srcRange.SetRange(template_start, template_end);//整体多行组复制摸板行组
                srcRange.Copy();

                //4.5 定位到新加入行的第一个单元格内
                //row1 = row1 - loopRow;//向上回退到新加入的行组
                //row2 = row2 - loopRow;

                //4.6 粘贴整体多行组,固定的摸板的格式和相关的文字说明
                desRange = operTable.Rows[row1].Range;//整体多行组粘贴摸板行组
                desRange.Paste();

xx1:        

goto xx2;      //跳过方法2 
//方法2  一行一行复制粘贴,代码很少
                for (int j = 0; j < loopRow; j++)
                {//插入需要重复循环的行数loopRow的空行,一行一行的复制粘贴
                    //复制模板行
                    srcRange=operTable.Rows[cur_row + j + j].Range;// 所以,粘贴几行,就要多加几行,j+j
                    srcRange.Copy();
                    //粘贴到目标行
                    desRange=operTable.Rows[cur_row + j].Range;//因为,新粘贴的行 在原来模板行的上面
                    desRange.Paste();
                }
                cur_row += loopRow;

xx2:


                //4.7 动态的数值加入
                for (int name_cell_idx = 0; name_cell_idx < nameCellCount; name_cell_idx++)
                {//循环命名单元格数量
                    //str = string.Format("{0}{1}", nameCellTag[name_cell_idx], nameCellRow[name_cell_idx]);
                    if (nameCellName[name_cell_idx].ToString() == "order_num")
                    {//序号
                        str = string.Format("{0}", dt_row_idx + 1);
                    }
                    else
                    {//以命名单元格的名称,来取数据表行的对应字段的值
                        str = dt.Rows[dt_row_idx][nameCellName[name_cell_idx]].ToString();

                    }
                 //   wdHelp.wordDoc.Tables[1].Cell(nameCellRow[name_cell_idx], nameCellColumn[name_cell_idx]).Range.Text = str;
                    operTable.Cell(nameCellRow[name_cell_idx], nameCellColumn[name_cell_idx]).Range.Text = str;
                    nameCellRow[name_cell_idx] += loopRow;//行号增加重复行的个数loopRow,准备下个循环,定位行使用
                }

            }
// 5 删除重复的摸板行,不再需要

            //方法1 多行组一次删除
            tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//找到行号最小的命名单元格,以它来定位
            row1 = tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
            row2 = row1 + loopRow - 1;//选择重复的行
            template_start = operTable.Cell(row1, 1).Range.Start;
            //template_end = operTable.Cell(row2, table_columns).Range.Start;//这样少一列
            template_end = operTable.Cell(row2 + 1, 1).Range.Start;//到下一行,第一个单元格
            tmpRange.SetRange(template_start, template_end);//整体多行组复制摸板行组
            tmpRange.Cut();

 

goto mm2://跳过方法2

            //方法2  一行一行地删除
            tmpRange = wdHelp.wordDoc.Bookmarks.get_Item(min_Name).Range;//找到行号最小的命名单元格,以它来定位
            row1 = tmpRange.Cells[1].RowIndex;//app.ActiveCell.Row;
            row2 = row1 + loopRow - 1;//选择重复的行
            for (int dd = 0; dd < loopRow; dd++)
            {
                operTable.Rows[row1].Delete();//同样的行号,因为删除前面的,后面向前移动
            }

mm2:

            //(三) 清除剪贴板,避免Excel关闭工作簿的时候出现提示
            //1 删除剪切板的内容,防止退出提示
            //app.CutCopyMode = flase;//Excel.XlCutCopyMode.xlCut;//删除剪切板的内容,防止退出提示
            //2 直接用range("A1").copy就行,不必把剪贴板都清空,这会影响其他进程的工作的
            //ws.Range[ws.Cells[1, 1], ws.Cells[1, 1]].Copy();
            //wdHelp.wordDoc.Tables[1].Cell(1, 1).Range.Copy();
            operTable.Cell(1, 1).Range.Copy();

            //(四) 结尾方面的工作
            try
            {//为了程序自动处理方便起见
                wdHelp.GoToBookMark("结论__");//结尾处的命名单元格,都以2个下划线__结尾
                wdHelp.InsertText("成功完成");
            }
            catch (System.Exception ex)
            {

            }
           
       }

    }
}

 

===== 2 整理成c# 操作 word的类函数===

 

//http://blog.csdn.net/skyering/article/details/8514879
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Word = Microsoft.Office.Interop.Word;

namespace word_namespace //CrossDomain.WebFinder
{
    public class WordHelper
    {
         public Word.ApplicationClass wordApp;
        public Word.Document wordDoc;
        object missing = System.Reflection.Missing.Value;

 


        public Word.ApplicationClass WordApplication
        {
            get
            {
                return wordApp;// _wordApplication;
            }
        }

        public Word.Document WordDocument
        {
            get
            {
                return wordDoc;
            }
        }


        public WordHelper()
        {
            wordApp = new Word.ApplicationClass();//_wordApplication
        }

        public WordHelper(Word.ApplicationClass wordApplication)
        {
            wordApp = wordApplication;//_wordApplication
        }

        public void CreateAndActive()
        {
            wordDoc = CreateOneDocument(missing, missing, missing, missing);
            wordDoc.Activate();
        }


        public bool OpenAndActive(string FileName, bool IsReadOnly, bool IsVisibleWin)
        {
            if (string.IsNullOrEmpty(FileName))
            {
                return false;
            }
            try
            {
                wordDoc = OpenOneDocument(FileName, missing, IsReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, IsVisibleWin, missing, missing, missing, missing);
                wordDoc.Activate();

                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Close()
        {
            if (wordDoc != null)
            {
                wordDoc.Close(ref missing, ref missing, ref missing);
                wordApp.Application.Quit(ref missing, ref missing, ref missing);//_wordApplication
            }
        }

        public void Save()
        {
            if (wordDoc == null)
            {
                wordDoc = wordApp.ActiveDocument;//_wordApplication
            }
            wordDoc.Save();
        }


        public void SaveAs(string FileName)
        {
            if (wordDoc == null)
            {
                wordDoc = wordApp.ActiveDocument;//_wordApplication
            }
            object objFileName = FileName;

            wordDoc.SaveAs(ref objFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }

         public Word.Document CreateOneDocument(object template, object newTemplate, object documentType, object visible)
        {
            return wordDoc = wordApp.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);//_wordApplication
        }

 
        public Word.Document OpenOneDocument(object FileName, object ConfirmConversions, object ReadOnly,
            object AddToRecentFiles, object PasswordDocument, object PasswordTemplate, object Revert,
            object WritePasswordDocument, object WritePasswordTemplate, object Format, object Encoding,
            object Visible, object OpenAndRepair, object DocumentDirection, object NoEncodingDialog, object XMLTransform)
        {
            try
            {//_wordApplication
                // return wordApp.Documents.Add(ref FileName, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles,
                return wordApp.Documents.Open(ref FileName, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles,
                   ref PasswordDocument, ref PasswordTemplate, ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate,
                   ref Format, ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog, ref XMLTransform);
            }
            catch
            {
                return null;
            }
        }

 

        public bool GoToBookMark(string bookMarkName)
        {
            //是否存在书签
            if (wordDoc.Bookmarks.Exists(bookMarkName))
            {
                object what = Word.WdGoToItem.wdGoToBookmark;
                object name = bookMarkName;
                GoTo(what, missing, missing, name);
                return true;
            }
            return false;
        }

       public void GoTo(object what, object which, object count, object name)
        {
            wordApp.Selection.GoTo(ref what, ref which, ref count, ref name);//_wordApplication
        }

 

        public void ReplaceBookMark(string bookMarkName, string text)
        {
            bool isExist = GoToBookMark(bookMarkName);
            if (isExist)
            {
                InsertText(text);
            }
        }

     public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive)
        {
            if (wordDoc == null)
            {
                wordDoc = wordApp.ActiveDocument;//_wordApplication

            }
            object findText = oldText;
            object replaceWith = newText;
            object wdReplace;
            object matchCase = isCaseSensitive;
            switch (replaceType)
            {
                case "All":
                    wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                    break;
                case "None":
                    wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                    break;
                case "FirstOne":
                    wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
                    break;
                default:
                    wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
                    break;
            }
            wordDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置

            return wordDoc.Content.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
                  ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                  ref wdReplace, ref missing, ref missing, ref missing, ref missing);
        }


        public void InsertText(string text)
        {
            wordApp.Selection.TypeText(text);//_wordApplication
        }

        public void InsertLineBreak()
        {
            wordApp.Selection.TypeParagraph();//_wordApplication
        }


        public void InsertPageBreak()
        {

            //插入分页   if(i!=DT.Rows.Count-1)
            {
                object mymissing = System.Reflection.Missing.Value;
                object myunit = Word.WdUnits.wdStory;
                wordApp.Selection.EndKey(ref myunit, ref mymissing);
                object pBreak = (int)Word.WdBreakType.wdPageBreak;
                wordApp.Selection.InsertBreak(ref pBreak);
            }
        }

        public void InsertPic(string fileName)
        {
            object range = wordApp.Selection.Range;//_wordApplication
            InsertPic(fileName, missing, missing, range);
        }

 
        public void InsertPic(string fileName, float width, float height)
        {
            object range = wordApp.Selection.Range;//_wordApplication
            InsertPic(fileName, missing, missing, range, width, height);
        }


        public void InsertPic(string fileName, float width, float height, string caption)
        {
            object range = wordApp.Selection.Range;//_wordApplication
            InsertPic(fileName, missing, missing, range, width, height, caption);
        }

 
       public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height, string caption)
        {//_wordApplication
            wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
            if (Width > 0)
            {
                wordApp.Selection.InlineShapes[1].Width = Width;//_wordApplication
            }
            if (Height > 0)
            {
                wordApp.Selection.InlineShapes[1].Height = Height;//_wordApplication
            }

            object Label = Word.WdCaptionLabelID.wdCaptionFigure;
            object Title = caption;
            object Title;
            object Position = Word.WdCaptionPosition.wdCaptionPositionBelow;
            object ExcludeLabel = true;
            wordApp.Selection.InsertCaption(ref Label, ref Title, ref TitleAutoText, ref Position, ref ExcludeLabel);//_wordApplication
            MoveRight();
        }

 
        public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height)
        {
            wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();//_wordApplication
            wordApp.Selection.InlineShapes[1].Width = Width;//_wordApplication
            wordApp.Selection.InlineShapes[1].Height = Height;//_wordApplication
            MoveRight();
        }


        public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range)
        {
            wordApp.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range);//_wordApplication
        }


        public void InsertBookMark(string bookMarkName)
        {
            //存在则先删除
            if (wordDoc.Bookmarks.Exists(bookMarkName))
            {
                DeleteBookMark(bookMarkName);
            }
            object range = wordApp.Selection.Range;//_wordApplication
            wordDoc.Bookmarks.Add(bookMarkName, ref range);

        }


        public void DeleteBookMark(string bookMarkName)
        {
            if (wordDoc.Bookmarks.Exists(bookMarkName))
            {
                var bookMarks = wordDoc.Bookmarks;
                for (int i = 1; i <= bookMarks.Count; i++)
                {
                    object index = i;
                    var bookMark = bookMarks.get_Item(ref index);
                    if (bookMark.Name == bookMarkName)
                    {
                        bookMark.Delete();
                        break;
                    }
                }
            }
        }

 
        public void DeleteAllBookMark()
        {
            for (; wordDoc.Bookmarks.Count > 0; )
            {
                object index = wordDoc.Bookmarks.Count;
                var bookmark = wordDoc.Bookmarks.get_Item(ref index);
                bookmark.Delete();
            }
        }
 
        public Word.Table AddTable(int NumRows, int NumColumns)
        {
            return AddTable(wordApp.Selection.Range, NumRows, NumColumns, missing, missing);//_wordApplication
        }


        public Word.Table AddTable(int NumRows, int NumColumns, Word.WdAutoFitBehavior AutoFitBehavior)
        {
            return AddTable(wordApp.Selection.Range, NumRows, NumColumns, missing, AutoFitBehavior);//_wordApplication
        }


        public Word.Table AddTable(Word.Range Range, int NumRows, int NumColumns, object DefaultTableBehavior, object AutoFitBehavior)
        {
            if (wordDoc == null)
            {
                wordDoc = wordApp.ActiveDocument;//_wordApplication
            }
            return wordDoc.Tables.Add(Range, NumRows, NumColumns, ref DefaultTableBehavior, ref AutoFitBehavior);
        }


        public Word.Row AddRow(Word.Table table)
        {
            return AddRow(table, missing);
        }


        public Word.Row AddRow(Word.Table table, object beforeRow)
        {
            return table.Rows.Add(ref beforeRow);
        }

        public void InsertRows(int numRows)
        {
            object NumRows = numRows;
            object wdCollapseStart = Word.WdCollapseDirection.wdCollapseStart;
            wordApp.Selection.InsertRows(ref NumRows);//_wordApplication
            wordApp.Selection.Collapse(ref wdCollapseStart);//_wordApplication
        }


        public void MoveLeft(Word.WdUnits unit = Word.WdUnits.wdCharacter, int count = 1, int extend_flag = 0)
        {
            object extend;
            if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
            else extend = missing;
            wordApp.Selection.MoveLeft(unit, count, extend);//_wordApplication
        }

 
        public void MoveUp(Word.WdUnits unit = Word.WdUnits.wdCharacter, int count = 1, int extend_flag = 0)
        {
            object extend;
            if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
            else extend = missing;
            wordApp.Selection.MoveUp(unit, count, extend);//_wordApplication
        }

        public void MoveRight(Word.WdUnits unit = Word.WdUnits.wdCharacter, int count = 1, int extend_flag = 0)
        {
            object extend;
            if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
            else extend = missing;
            wordApp.Selection.MoveRight(unit, count, extend);//_wordApplication
        }

        public void MoveDown(Word.WdUnits unit = Word.WdUnits.wdCharacter, int count = 1, int extend_flag = 0)
        {
            object extend;
            if (extend_flag == 1) extend = Word.WdMovementType.wdExtend;
            else extend = missing;
            wordApp.Selection.MoveDown(unit, count, extend);//_wordApplication
        }
        //2 另外的地方复制过来
 
        public void SetLinesPage(int size = 40)
        {
            wordApp.ActiveDocument.PageSetup.LinesPage = size;
        }

        public void SetPageHeaderFooter(string context, int HeaderFooter = 0)
        {
           
            //            wordApp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;
            //            wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
            //            wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(context);
            //            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //跳出页眉设置   
            //            wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
            //
            添加页眉方法二:
            if (wordApp.ActiveWindow.ActivePane.View.Type == Word.WdViewType.wdNormalView ||
                wordApp.ActiveWindow.ActivePane.View.Type == Word.WdViewType.wdOutlineView)
            {
                wordApp.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
            }
            if (HeaderFooter == 0)
            {//设置页眉内容";
                wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
            }
            else
            {//设置页脚内容";
                wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            }
            wordApp.Selection.HeaderFooter.LinkToPrevious = false;
            wordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordApp.Selection.HeaderFooter.Range.Text = context;// "页眉 页脚 内容";

            //跳出页眉页脚设置
            wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

        }

        public void InsertFormatText(string context, int fontSize, Word.WdColor fontColor, int fontBold, string familyName, Word.WdParagraphAlignment align)
        {
            //设置字体样式以及方向   
            wordApp.Application.Selection.Font.Size = fontSize;
            wordApp.Application.Selection.Font.Bold = fontBold;
            wordApp.Application.Selection.Font.Color = fontColor;
            wordApp.Selection.Font.Name = familyName;
            wordApp.Application.Selection.ParagraphFormat.Alignment = align;
            wordApp.Application.Selection.TypeText(context);

        }
 
        public Word.Table CreatTable(int rowNum, int cellNum)
        {
            return this.wordDoc.Tables.Add(wordApp.Selection.Range, rowNum, cellNum, ref missing, ref missing);
        }

        public void setPageLay(string paper = "A4", int orient = 0)
        {
            //页面设置,设置页面为纵向布局,设置纸张类型为A4纸
            if (orient == 0)
            {
                wordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

            }
            else
            {
                wordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait;

            }
            if (paper == "A4")
            {
                wordDoc.PageSetup.PageWidth = wordApp.CentimetersToPoints(29.7F);
                wordDoc.PageSetup.PageHeight = wordApp.CentimetersToPoints(21F);

            }

        }

        public Word.Table getTable(int index)
        {
            //    int table_num = this.wordDoc.Tables.Count;
            //    Word.Tables tables = wordDoc.Tables;
            //    return wordDoc.Content.Tables[index];
            //    wordDoc.Tables.Item(index);


            int no = 0;
            foreach (Word.Table table in wordDoc.Tables)//tables)
            {
                if (no == index) return table;
                no++;
            }
            return null;
        }

 
        public void SetColumnWidth(float[] widths, Word.Table tb)
        {
            if (widths.Length > 0)
            {
                int len = widths.Length;
                for (int i = 0; i < len; i++)
                {
                    tb.Columns[i + 1].Width = widths[i];

                }
            }
        }
 
        public void MergeColumn(Word.Table tb, Word.Cell[] cells)
        {
            if (cells.Length > 1)
            {
                Word.Cell c = cells[0];
                int len = cells.Length;
                for (int i = 1; i < len; i++)
                {
                    c.Merge(cells[i]);
                }
            }
            wordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

        }
  }

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值