C#實現通過模板自動建立Word文檔的方法

來源:互聯網
上載者:User

標籤:ppa   執行   private   儲存   visible   決定   sre   插入圖片   程式設計   

本文執行個體講述了C#實現通過模板自動建立Word文檔的方法,是非常實用的技巧。分享給大家供大家參考。具體實現方法如下:

引言:前段時間有項目要用c#產生Word格式的計算報告,通過網路尋找到很多內容,但是都很淩亂,於是自己決定將具體的步驟總結整理出來,以便於更好的交流和以後相似問題可以迅速的解決!

現通過具體的樣本示範具體的步驟:


第一步,製作模板



1.建立一個文檔,設定文檔內容。

2.在相應位置插入書籤;將滑鼠定位到要插入書籤的位置,點擊“插入”>“書籤”,彈出對話方塊,輸入書籤名,點擊“添加”按鈕。

3.儲存模板,命名為“模板1.dot”或者“模板1.doc”


第二步,設定項目中的引用

1.右擊“方案總管”中的項目目錄下的“引用”,選擇“添加引用”,開啟“添加引用”對話方塊

2.在“添加引用”對話方塊中,選擇“COM”>“Microsoft Word 11.0 Object Library”,點擊“確定”按鈕

3.相同操作開啟“添加引用”對話方塊中,選擇“瀏覽”項,尋找到”Microsoft.Office.Interop.Word.dll”檔案,選中它,點擊“確定”按鈕

注意:

此處要尋找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數字


第三步,編碼

這一步分成兩個部分

第一部分,Report類的編碼

這部分我已經封裝好,為檔案“Report.cs”,可以直接使用

具體實現代碼如下:(代碼中有比較詳細的注釋)

using System;using System.Collections.Generic;using System.Text;using Microsoft.Office.Interop.Word;namespace MYNAMESPACE //這邊需要換成自己的命名空間名{  classReport  {    private_ApplicationwordApp= null;    private_DocumentwordDoc= null;    public_ApplicationApplication    {      get      {        return wordApp;      }      set      {        wordApp = value;      }    }    public_DocumentDocument    {      get      {        return wordDoc;      }      set      {        wordDoc = value;      }    }    //通過模板建立新文檔    publicvoidCreateNewDocument(stringfilePath)    {      killWinWordProcess();      wordApp= new ApplicationClass();      wordApp.DisplayAlerts =WdAlertLevel.wdAlertsNone;      wordApp.Visible =false;      objectmissing =System.Reflection.Missing.Value;      objecttemplateName =filePath;      wordDoc= wordApp.Documents.Open(reftemplateName, refmissing,        ref missing, ref missing,ref missing, ref missing, refmissing,        ref missing, ref missing,ref missing, ref missing, refmissing,        ref missing, ref missing,ref missing, ref missing);    }    //儲存新檔案    publicvoidSaveDocument(stringfilePath)    {      objectfileName =filePath;      objectformat =WdSaveFormat.wdFormatDocument;//儲存格式      objectmiss =System.Reflection.Missing.Value;      wordDoc.SaveAs(reffileName, ref format, ref miss,        ref miss, ref miss,ref miss, ref miss,        ref miss, ref miss,ref miss, ref miss,        ref miss, ref miss,ref miss, ref miss,        ref miss);      //關閉wordDoc,wordApp對象      objectSaveChanges =WdSaveOptions.wdSaveChanges;      objectOriginalFormat =WdOriginalFormat.wdOriginalDocumentFormat;      objectRouteDocument =false;      wordDoc.Close(refSaveChanges, refOriginalFormat, refRouteDocument);      wordApp.Quit(refSaveChanges, refOriginalFormat, refRouteDocument);    }    //在書籤處插入值    publicboolInsertValue(stringbookmark, stringvalue)    {      objectbkObj =bookmark;      if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark))      {        wordApp.ActiveDocument.Bookmarks.get_Item(refbkObj).Select();        wordApp.Selection.TypeText(value);        return true;      }      returnfalse;    }    //插入表格,bookmark書籤    publicTableInsertTable(stringbookmark, int rows, int columns,float width)    {      objectmiss =System.Reflection.Missing.Value;      objectoStart =bookmark;      Rangerange =wordDoc.Bookmarks.get_Item(refoStart).Range;//表格插入位置      TablenewTable =wordDoc.Tables.Add(range,rows, columns, ref miss, refmiss);      //設定表的格式      newTable.Borders.Enable =1; //允許有邊框,預設沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)      newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//邊框寬度      if(width != 0)      {        newTable.PreferredWidth=width;//表格寬度      }      newTable.AllowPageBreaks =false;      returnnewTable;    }    //合併儲存格 表名,開始行號,開始列號,結束行號,結束列號    publicvoidMergeCell(Microsoft.Office.Interop.Word.Tabletable, int row1, int column1,int row2, int column2)    {      table.Cell(row1,column1).Merge(table.Cell(row2,column2));    }    //設定表格內容對齊Align水平方向,Vertical垂直方向(靠左對齊,置中對齊,靠右對齊分別對應Align和Vertical的值為-1,0,1)    publicvoidSetParagraph_Table(Microsoft.Office.Interop.Word.Tabletable, int Align, int Vertical)    {      switch(Align)      {        case -1:table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;break;//靠左對齊        case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;//水平置中        case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;//靠右對齊      }      switch(Vertical)      {        case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;//頂端對齊        case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;//垂直置中        case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;//底端對齊      }    }    //設定表格字型    publicvoidSetFont_Table(Microsoft.Office.Interop.Word.Tabletable, string fontName, double size)    {      if(size != 0)      {        table.Range.Font.Size =Convert.ToSingle(size);      }      if(fontName !="")      {        table.Range.Font.Name =fontName;      }    }    //是否使用邊框,n表格的序號,use是或否    publicvoidUseBorder(int n,bool use)    {      if(use)      {        wordDoc.Content.Tables[n].Borders.Enable =1; //允許有邊框,預設沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)      }      else      {        wordDoc.Content.Tables[n].Borders.Enable =2; //允許有邊框,預設沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過)      }    }    //給表格插入一行,n表格的序號從1開始記    publicvoidAddRow(int n)    {      objectmiss =System.Reflection.Missing.Value;      wordDoc.Content.Tables[n].Rows.Add(refmiss);    }    //給表格添加一行    publicvoidAddRow(Microsoft.Office.Interop.Word.Tabletable)    {      objectmiss =System.Reflection.Missing.Value;      table.Rows.Add(refmiss);    }    //給表格插入rows行,n為表格的序號    publicvoidAddRow(int n, int rows)    {      objectmiss =System.Reflection.Missing.Value;      Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];      for(inti = 0; i < rows; i++)      {        table.Rows.Add(refmiss);      }    }    //給表格中儲存格插入元素,table所在表格,row行號,column列號,value插入的元素    publicvoidInsertCell(Microsoft.Office.Interop.Word.Tabletable, int row, int column,string value)    {      table.Cell(row,column).Range.Text =value;    }    //給表格中儲存格插入元素,n表格的序號從1開始記,row行號,column列號,value插入的元素    publicvoidInsertCell(int n, int row,int column, string value)    {      wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value;    }    //給表格插入一行資料,n為表格的序號,row行號,columns列數,values插入的值    publicvoidInsertCell(int n, int row,int columns, string[] values)    {      Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];      for(inti = 0; i < columns; i++)      {        table.Cell(row,i + 1).Range.Text =values[i];      }    }    //插入圖片    publicvoidInsertPicture(stringbookmark, stringpicturePath, floatwidth, float hight)    {      object miss = System.Reflection.Missing.Value;      objectoStart =bookmark;      ObjectlinkToFile =false;    //圖片是否為外部連結      ObjectsaveWithDocument =true; //圖片是否隨文檔一起儲存      objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;//圖片插入位置      wordDoc.InlineShapes.AddPicture(picturePath,ref linkToFile, ref saveWithDocument, refrange);      wordDoc.Application.ActiveDocument.InlineShapes[1].Width=width; //設定圖片寬度      wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; //設定圖片高度    }    //插入一段文字,text為文字內容    publicvoidInsertText(stringbookmark, stringtext)    {      objectoStart =bookmark;      objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;      Paragraphwp =wordDoc.Content.Paragraphs.Add(refrange);      wp.Format.SpaceBefore= 6;      wp.Range.Text =text;      wp.Format.SpaceAfter =24;      wp.Range.InsertParagraphAfter();      wordDoc.Paragraphs.Last.Range.Text ="\n";    }    //殺掉winword.exe進程    publicvoidkillWinWordProcess()    {      System.Diagnostics.Process[]processes=System.Diagnostics.Process.GetProcessesByName("WINWORD");      foreach (System.Diagnostics.Processprocess in processes)      {        bool b = process.MainWindowTitle=="";        if (process.MainWindowTitle =="")        {          process.Kill();        }      }    }  }}


第二部分,具體產生文檔的編碼

代碼見下文:


1.首先需要載入模板


Report report =new Report();

report.CreateNewDocument(TemPath); //模板路徑


2.插入一個值


report.InsertValue(“Bookmark_value”,”世界盃”);//在書籤“Bookmark_value”處插入值


3.建立一個表格


Table table =report.InsertTable(“Bookmark_table”, 2, 3, 0); //在書籤“Bookmark_table”處插入2行3列行寬最大的表


4.合併儲存格


report.MergeCell(table, 1, 1, 1, 3); //表名,開始行號,開始列號,結束行號,結束列號


5.表格添加一行


report.AddRow(table); //表名


6.在儲存格中插入值


report.InsertCell(table, 2, 1,”R2C1″);//表名,行號,列號,值


7.設定表格中文字的對齊


report.SetParagraph_Table(table, -1, 0);//水平方向靠左對齊,垂直方向置中對齊


8.設定表格字型


report.SetFont_Table(table,”宋體”, 9);//宋體9磅


9.給現有的表格添加一行


report.AddRow(1);//給模板中第一個表格添加一行


10.確定現有的表格是否使用邊框


report.UseBorder(1,true); //模板中第一個表格使用實線邊框


11.給現有的表格添加多行


report.AddRow(1, 2);//給模板中第一個表格插入2行


12.給現有的表格插入一行資料


string[] values={“英超”, “意甲”, “德甲”,”西甲”, “法甲” };

report.InsertCell(1, 2, 5,values); //給模板中第一個表格的第二行的5列分別插入資料


13.插入圖片


string picturePath = @”C:\Documents and Settings\Administrator\案頭\1.jpg”;

report.InsertPicture(“Bookmark_picture”,picturePath, 150, 150); //書籤位置,圖片路徑,圖片寬度,圖片高度


14.插入一段文字


string text = “長期從事電腦操作者,應多吃一些新鮮的蔬菜和水果,同時增加維生素A、B1、C、E的攝入。為預防角膜乾燥、眼乾澀、視力下降、甚至出現夜盲等,電 腦操作者應多吃富含維生素A的食物,如豆製品、魚、牛奶、核桃、青菜、大白菜、空心菜、西紅柿及新鮮水果等。”;

report.InsertText(“Bookmark_text”,text);


15.最後儲存文檔


report.SaveDocument(RepPath); //文檔路徑


第四步,運行程式產生文檔,並查看產生的文檔

希望本文所述對大家的C#程式設計有所協助。

除聲明外, 跑步客文章均為原創,轉載請以連結形式標明本文地址
  C#實現通過模板自動建立Word文檔的方法

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23495.html






相關內容C# FileStream???t?áD′?ê?aC#簡單實現防止多個程式啟動並執行方法C#訪問SQL Server資料庫的實現方法C#實現利用Windows API讀寫INI檔案的方法
C#產生Word文檔程式碼範例C#中的檔案路徑擷取函數和檔案名稱字擷取函數小結C#實現終止正在執行的線程C#使用ping命令的兩個例子

C#實現通過模板自動建立Word文檔的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.