1. 程式人生 > >c# 操作Word總結

c# 操作Word總結

Word物件模型 (.Net Perspective)
  五大物件
Application :代表Microsoft Word應用程式本身
  是Document和Selection的基類。通過Application的屬性和方法,我們可以控制Word的大環境。
Document :代表一個Word文件
  當你新建一個Word文件或者開啟一個已有的Word文件,你將建立一個Document物件,該物件被加入到Words Documents Collection中。擁有焦點的Document稱為ActiveDocument,可以通過Application物件的ActiveDocument屬性獲得當前文件物件
Selection :

代表當前選中的區域(高亮),沒有選中區域時代表游標點
  它通常是高亮顯示的(例如,你要改變一段文字的字型,你首先得選中這段文字,那麼選中的這塊區域就是當前文件的Selection物件所包含的區域)
Bookmarks :書籤
  1>書籤一般有名字
  2>Saved with the document,且文件關閉了之後書籤繼續存在
  3>書籤通常是隱藏的,但也可以通過程式碼設定其為可見

Range :代表一塊區域,與Selection類似,不過一般不可見
  1>包含一個起始位置和一個結束位置
  2>它可以包含游標點,一段文字或者整個文件
  3>它包含空格,tab以及paragraph marks
  4>它可以是當前選中的區域,當然也可以不是當前選中區域
  5>它被動態建立
  6>當你在一個Range的末尾插入文字,這將擴充套件該Range


  word文件物件的結構圖


關於物件的詳細使用,可以參考msdn api

例項使用  

建立Word 文件所使用的主要方法是通過微軟公司提供的Microsoft Word X Object Library,
其中X 為版本號。Word2010對應14.0, Word 2007 對應12.0,Word 2003 對應11.0。
通過在專案中新增該元件,即可使用微軟公司提供的方法建立相應版本的Word 文件。
在例項中我將所要生成word的格式設定為2003版本

新建一個winForm專案檔案,
Com元件中新增 Microsoft Word 12.0 Object Library,引用面板中多出Microsoft.Office.Core、Microsoft.Office.Interop.Word兩個引用。
在類檔案中新增應用如下:
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

  下面從word建立、格式設定、文字新增、圖片新增、表格新增展示部分程式碼:

複製程式碼
void CreateWord()
        {
            object path;//檔案路徑
            string strContent;//檔案內容
            MSWord.Application wordApp;//Word應用程式變數
            MSWord.Document wordDoc;//Word文件變數
            path = "d:\\myWord.doc";//儲存為Word2003文件
           // path = "d:\\myWord.doc";//儲存為Word2007文件
            wordApp = new MSWord.ApplicationClass();//初始化
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由於使用的是COM 庫,因此有許多變數需要用Missing.Value 代替
            Object Nothing = Missing.Value;
            //新建一個word物件
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //WdSaveDocument為Word2003文件的儲存格式(文件字尾.doc)\wdFormatDocumentDefault為Word2007的儲存格式(文件字尾.docx)
            object format = MSWord.WdSaveFormat.wdFormatDocument;
           //將wordDoc 文件物件的內容儲存為DOC 文件,並儲存到path指定的路徑
            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.Close(ref Nothing, ref Nothing, ref Nothing);
            //關閉wordApp元件物件
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Response.Write("<script>alert('" + path + ": Word文件建立完畢!');</script>");
        }
複製程式碼 複製程式碼
private void SetWordStyle()
        {
            object path;//檔案路徑
            string strContent;//檔案內容
            MSWord.Application wordApp;//Word應用程式變數
            MSWord.Document wordDoc;//Word文件變數
            path = "d:\\myWord.doc";//儲存為Word2003文件
            // path = "d:\\myWord.doc";//儲存為Word2007文件
            wordApp = new MSWord.ApplicationClass();//初始化
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            //頁面設定
            wordDoc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;//設定紙張樣式
            wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.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 = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;//檢視樣式
            wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;//進入頁首設定,其中頁首邊距在頁面設定中已完成
            wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

            //插入頁首圖片(測試結果圖片未插入成功)
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            string headerfile = "d:\\header.jpg";
            Microsoft.Office.Interop.Word.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);
            shape1.Height = 20;
            shape1.Width = 80;
            wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文件頁首");
            //去掉頁首的橫線
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
            wordApp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
            wordApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;//退出頁首設定

            //為當前頁新增頁碼
            Microsoft.Office.Interop.Word.PageNumbers pns = wordApp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//獲取當前頁的號碼
            pns.NumberStyle = Microsoft.Office.Interop.Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
            pns.HeadingLevelForChapter = 0;
            pns.IncludeChapterNumber = false;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber = 0;
            object pagenmbetal = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;//將號碼設定在中間
            object first = true;
            wordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);


            object format = MSWord.WdSaveFormat.wdFormatDocument;
            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.Close(ref Nothing, ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Response.Write("<script>alert('" + path + ": Word文件格式設定完畢!');</script>");
        }
複製程式碼

效果圖:

複製程式碼
private void AddWordText()
        {
            object path;//檔案路徑
            string strContent;//檔案內容
            MSWord.Application wordApp;//Word應用程式變數
            MSWord.Document wordDoc;//Word文件變數
            path = "d:\\myWord.doc";//儲存為Word2003文件
            // path = "d:\\myWord.doc";//儲存為Word2007文件
            wordApp = new MSWord.ApplicationClass();//初始化
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            wordApp.Selection.ParagraphFormat.LineSpacing = 35f;//設定文件的行間距
            //寫入普通文字
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行縮排的長度
            strContent = "c#向Word寫入文字   普通文字:\n";  
            wordDoc.Paragraphs.Last.Range.Text = strContent;

            //將文件的前三個字替換成"asdfasdf",並將其顏色設為藍色
            object start = 0;
            object end = 3;
            Microsoft.Office.Interop.Word.Range rang = wordDoc.Range(ref start, ref end);
            rang.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBrightGreen;
            rang.Text = "我是替換文字";
            wordDoc.Range(ref start, ref end);



            //寫入黑體文字
            object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行縮排的長度
            strContent = "黑體文字\n ";//在文字中使用'\n'換行
            wordDoc.Paragraphs.Last.Range.Font.Name = "黑體";
            wordDoc.Paragraphs.Last.Range.Text = strContent;
           // wordApp.Selection.Text = strContent;
            //寫入加粗文字
            strContent = "加粗文字\n ";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordDoc.Paragraphs.Last.Range.Font.Bold = 1;//Bold=0為不加粗
            wordDoc.Paragraphs.Last.Range.Text = strContent;
            //  wordApp.Selection.Text = strContent;
            //寫入15號字型文字
            strContent = "15號字型文字\n ";
            wordApp.Selection.EndKey(ref unite, ref Nothing);
           
            wordDoc.Paragraphs.Last.Range.Font.Size = 15;
            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;

            object format = MSWord.WdSaveFormat.wdFormatDocument;
            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.Close(ref Nothing, ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Response.Write("<script> alert('" + path + ": Word文件寫入文字完畢!');</script>");
        }
複製程式碼

效果圖:

複製程式碼
    private void AddWordPic()
        {
            object path;//檔案路徑
            string strContent;//檔案內容
            MSWord.Application wordApp;//Word應用程式變數
            MSWord.Document wordDoc;//Word文件變數
            path = "d:\\myWord.doc";//儲存為Word2003文件
            // path = "d:\\myWord.doc";//儲存為Word2007文件
            wordApp = new MSWord.ApplicationClass();//初始化
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            string filename = "d:\\kk.jpg";
            //定義要向文件中插入圖片的位置
            object range = wordDoc.Paragraphs.Last.Range;
            //定義該圖片是否為外部連結
            object linkToFile = false;//預設
            //定義插入的圖片是否隨word一起儲存
            object saveWithDocument = true;
            //向word中寫入圖片
            wordDoc.InlineShapes.AddPicture(filename, ref Nothing, ref Nothing, ref Nothing);

            object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中顯示圖片
            wordDoc.InlineShapes[1].Height = 130;
            wordDoc.InlineShapes[1].Width = 200;
            wordDoc.Content.InsertAfter("\n");
            wordApp.Selection.EndKey(ref unite, ref Nothing);
            wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordApp.Selection.Font.Size = 10;//字型大小
            wordApp.Selection.TypeText("圖1 測試圖片\n");


            object format = MSWord.WdSaveFormat.wdFormatDocument;
            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.Close(ref Nothing, ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            Response.Write("<script>alert('" + path + ": Word文件建立圖片完畢!');</script>");
        }
複製程式碼

效果圖:

複製程式碼
private void AddWordTable()
        {
            object path;//檔案路徑
            string strContent;//檔案內容
            MSWord.Application wordApp;//Word應用程式變數
            MSWord.Document wordDoc;//Word文件變數
            path = "d:\\myWord.doc";//儲存為Word2003文件
            // path = "d:\\myWord.doc";//儲存為Word2007文件
            wordApp = new MSWord.ApplicationClass();//初始化
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            Object Nothing = Missing.Value;
            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            int tableRow = 6;
            int tableColumn = 6;
            //定義一個word中的表格物件
            MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing);


            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 = 45;
            //向新新增的行的單元格中新增圖片
            string FileName