1. 程式人生 > >C#來操作Word

C#來操作Word

user 顏色 成功 arp 設置 雙線 dir atl 就是

創建Word;

插入文字,選擇文字,編輯文字的字號、粗細、顏色、下劃線等;

設置段落的首行縮進、行距;

設置頁面頁邊距和紙張大小;

設置頁眉、頁碼;

插入圖片,設置圖片寬高以及給圖片添加標題;

插入表格,格式化表格,往表格中插入數據;

保存Word,打印Word;

重新打開Word等。

/*
1. 添加引用COM裏面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本)

2. 導命名空間

using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;

3. 把引用中的Microsoft.Office.Interop.Word的“屬性”中的嵌入互操作設為False
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;

namespace Console_WordSkill_All
{
    class Program
    {
        static void Main(string[] args)
        {
            object path;                              //文件路徑變量
            string strContent;                        //文本內容變量
            MSWord.Application wordApp;                   //Word應用程序變量 
            MSWord.Document wordDoc;                  //Word文檔變量
            
            path = Environment.CurrentDirectory + "\\MyWord_Print.doc";
            wordApp = new MSWord.ApplicationClass(); //初始化

            wordApp.Visible = true;//使文檔可見

            //如果已存在,則刪除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }

            //由於使用的是COM庫,因此有許多變量需要用Missing.Value代替
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            #region 頁面設置、頁眉圖片和文字設置,最後跳出頁眉設置

            //頁面設置
            wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//設置紙張樣式為A4紙
            wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式為垂直方向
            wordDoc.PageSetup.TopMargin = 57.0f;
            wordDoc.PageSetup.BottomMargin = 57.0f;
            wordDoc.PageSetup.LeftMargin = 57.0f;
            wordDoc.PageSetup.RightMargin = 57.0f;
            wordDoc.PageSetup.HeaderDistance = 30.0f;//頁眉位置

            //設置頁眉
            wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通視圖(即頁面視圖)樣式
            wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//進入頁眉設置,其中頁眉邊距在頁面設置中已完成
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//頁眉中的文字右對齊


            //插入頁眉圖片(測試結果圖片未插入成功)
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg";
            MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);
            shape1.Height = 5;//強行設置貌似無效,圖片沒有按設置的縮放——圖片的比例並沒有改變。
            shape1.Width = 20;
            wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文檔頁眉");//在頁眉的圖片後面追加幾個字
            
            //去掉頁眉的橫線
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone;
            wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false;
            wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;//退出頁眉設置
            #endregion

            #region 頁碼設置並添加頁碼

            //為當前頁添加頁碼
            MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//獲取當前頁的號碼
            pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//設置頁碼的風格,是Dash形還是圓形的
            pns.HeadingLevelForChapter = 0;
            pns.IncludeChapterNumber = false;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber = 0; //開始頁頁碼?
            object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//將號碼設置在中間
            object first = true;
            wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

            #endregion

            #region 行間距與縮進、文本字體、字號、加粗、斜體、顏色、下劃線、下劃線顏色設置

            wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//設置文檔的行間距
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行縮進的長度
            //寫入普通文本
            strContent = "我是普通文本\n";
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            wordDoc.Paragraphs.Last.Range.Text = "我再加一行試試,這裏不加‘\\n‘";
            //直接添加段,不是覆蓋( += )
            wordDoc.Paragraphs.Last.Range.Text += "不會覆蓋的,";

            //添加在此段的文字後面,不是新段落
            wordDoc.Paragraphs.Last.Range.InsertAfter("這是後面的內容\n");

            //將文檔的前4個字替換成"哥是替換文字",並將其顏色設為紅色
            object start = 0;
            object end = 4;
            MSWord.Range rang = wordDoc.Range(ref start, ref end);
            rang.Font.Color = MSWord.WdColor.wdColorRed;
            rang.Text = "哥是替換文字";
            wordDoc.Range(ref start, ref end);

            //寫入黑體文本
            object unite = MSWord.WdUnits.wdStory;
            wordApp.Selection.EndKey(ref unite, ref Nothing);//將光標移到文本末尾
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行縮進的長度
            strContent = "這是黑體文本\n";
            wordDoc.Paragraphs.Last.Range.Font.Name = "黑體";
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入加粗文本
            strContent = "這是粗體文本\n"; //
            wordApp.Selection.EndKey(ref unite, ref Nothing);//這一句不加,有時候好像也不出問題,不過還是加了安全
            wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入15號字體文本
            strContent = "我這個文本的字號是15號,而且是宋體\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Size = 15;
            wordDoc.Paragraphs.Last.Range.Font.Name = "宋體";
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入斜體文本
            strContent = "我是斜體字文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入藍色文本
            strContent = "我是藍色的文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入下劃線文本
            strContent = "我是下劃線文本\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //寫入紅色下畫線文本
            strContent = "我是點線下劃線,並且下劃線是紅色的\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy;
            wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //取消下劃線,並且將字號調整為12號
            strContent = "我他媽不要下劃線了,並且設置字號為12號,黑色不要斜體\n";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Size = 12;
            wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone;
            wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;
            wordDoc.Paragraphs.Last.Range.Font.Italic = 0;
            wordDoc.Paragraphs.Last.Range.Text = strContent;
            

            #endregion


            #region 插入圖片、居中顯示,設置圖片的絕對尺寸和縮放尺寸,並給圖片添加標題

            wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾
            //圖片文件的路徑
            string filename = Environment.CurrentDirectory + "\\6.jpg";
            //要向Word文檔中插入圖片的位置
            Object range = wordDoc.Paragraphs.Last.Range;
            //定義該插入的圖片是否為外部鏈接
            Object linkToFile = false;               //默認,這裏貌似設置為bool類型更清晰一些
            //定義要插入的圖片是否隨Word文檔一起保存
            Object saveWithDocument = true;              //默認
            //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片
            wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中顯示圖片

            //設置圖片寬高的絕對大小

            //wordDoc.InlineShapes[1].Width = 200;
            //wordDoc.InlineShapes[1].Height = 150;
            //按比例縮放大小

            wordDoc.InlineShapes[1].ScaleWidth = 20;//縮小到20% ?
            wordDoc.InlineShapes[1].ScaleHeight = 20;

            //在圖下方居中添加圖片標題

            wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透
            wordApp.Selection.EndKey(ref unite, ref Nothing);          
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            wordApp.Selection.Font.Size = 10;//字體大小
            wordApp.Selection.TypeText("圖1 測試圖片\n");

            #endregion

            #region 添加表格、填充數據、設置表格行列寬高、合並單元格、添加表頭斜線、給單元格添加圖片
            wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透
            wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
            //object WdLine2 = MSWord.WdUnits.wdLine;//換一行;  
            //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行輸入表格,這樣表格就在文字下方了,不過這是非主流的方法

            //設置表格的行數和列數
            int tableRow = 6;
            int tableColumn = 6;

            //定義一個Word中的表格對象
            MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
            tableRow, tableColumn, ref Nothing, ref Nothing);

            //默認創建的表格沒有邊框,這裏修改其屬性,使得創建的表格帶有邊框 
            table.Borders.Enable = 1;//這個值可以設置得很大,例如5、13等等

            //表格的索引是從1開始的。
            wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行";
            for (int i = 1; i < tableRow; i++)
            {
                for (int j = 1; j < tableColumn; j++)
                {
                    if (i == 1)
                    {
                        table.Cell(i, j + 1).Range.Text = "Column " + j;//填充每列的標題
                    }
                    if (j == 1)
                    {
                        table.Cell(i + 1, j).Range.Text = "Row " + i; //填充每行的標題
                    }
                    table.Cell(i + 1, j + 1).Range.Text = i + "行 " + j + "列";  //填充表格的各個小格子
                }
            }


            //添加行
            table.Rows.Add(ref Nothing);
            table.Rows[tableRow + 1].Height = 35;//設置新增加的這行表格的高度
            //向新添加的行的單元格中添加圖片
            string FileName = Environment.CurrentDirectory + "\\6.jpg";//圖片所在路徑
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//選中要添加圖片的單元格
            wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

            //由於是本文檔的第2張圖,所以這裏是InlineShapes[2]
            wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//圖片寬度
            wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//圖片高度
            
            // 將圖片設置為四周環繞型
            MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape();
            s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;


            //設置table樣式
            table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規則是:行高有最低值下限?
            table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));// 

            table.Range.Font.Size = 10.5F;
            table.Range.Font.Bold = 0;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中
            table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直貼到底部
            //設置table邊框樣式
            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;//表格外框是雙線
            table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格內框是單線

            table.Rows[1].Range.Font.Bold = 1;//加粗
            table.Rows[1].Range.Font.Size = 12F;
            table.Cell(1, 1).Range.Font.Size = 10.5F;
            wordApp.Selection.Cells.Height = 30;//所有單元格的高度

            //除第一行外,其他行的行高都設置為20
            for (int i = 2; i <= tableRow; i++)
            {
                table.Rows[i].Height = 20;
            }

            //將表格左上角的單元格裏的文字(“行” 和 “列”)居右
            table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
            //將表格左上角的單元格裏面下面的“列”字移到左邊,相比上一行就是將ParagraphFormat改成了Paragraphs[2].Format
            table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;

            table.Columns[1].Width = 50;//將第 1列寬度設置為50

            //將其他列的寬度都設置為75
            for (int i = 2; i <= tableColumn; i++)
            {
                table.Columns[i].Width = 75;
            }


            //添加表頭斜線,並設置表頭的樣式
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true;
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed;
            table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;

            //合並單元格
            table.Cell(4, 4).Merge(table.Cell(4, 5));//橫向合並

            table.Cell(2, 3).Merge(table.Cell(4, 3));//縱向合並,合並(2,3),(3,3),(4,3)

            #endregion

            wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾

            wordDoc.Content.InsertAfter("\n");
            wordDoc.Content.InsertAfter("就寫這麽多,算了吧!2016.09.27");
            


            //WdSaveFormat為Word 2003文檔的保存格式
            object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault
            //將wordDoc文檔對象的內容保存為DOCX文檔
            wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //關閉wordDoc文檔對象

            //看是不是要打印
            //wordDoc.PrintOut();



            wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //關閉wordApp組件對象
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Console.WriteLine(path + " 創建完畢!");
            Console.ReadKey();


            //我還要打開這個文檔玩玩
            MSWord.Application app = new MSWord.Application();
            MSWord.Document doc = null;
            try
            {
                
                object unknow = Type.Missing;
                app.Visible = true;
                string str = Environment.CurrentDirectory + "\\MyWord_Print.doc";
                object file = str;
                doc = app.Documents.Open(ref file,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow, ref unknow,
                    ref unknow, ref unknow, ref unknow);
                string temp = doc.Paragraphs[1].Range.Text.Trim();
                Console.WriteLine("你他媽輸出temp幹嘛?");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            wordDoc = doc;
            wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再寫了,就寫這麽多吧";

            Console.ReadKey();
        }

    }
}

  

C#來操作Word