在.net環境裏對word的操作主要包括:
1.創建word文檔
2.往word中寫入內容
3.保存
主要是往word寫入的內容,包括標題,表格等等.
在word的版本中.net支持2003版本,
在創建word之前要做的工作:
1>創建一個.net的項目
2>添加引用:選擇.Net->選擇Microsoft Word 11.0 Object Library
3>添加引用:在office安裝程序中找到Office.dll和Microsoft.Office.Interop.Word.dll。
下面就可以編寫代碼了
以下是給出例子加以講解,對word的操作就變得非常簡單了,網上的許多資料都很繁瑣
在設計的時候,可以先創建一個操作類這樣就可以節省很多代碼,而且用起來非常的方便
下面是ClassWord.cs文件
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using Microsoft.Office.Core;
11using Microsoft.Office.Interop.Word;
12
13/// <summary>
14/// ClassWord 的摘要說明
15/// </summary>
16public class ClassWord
17{
18 Word.Application wApp = null;
19 Word.Document wDoc = null, oDoc = null;
20 Word.Documents Docs = null;
21 private object strTemplate = "";
22 private object oEndOfDoc = "//endofdoc";
23 private object oMissing = System.Reflection.Missing.Value;//System.Reflection.Missing.Value;
24 Word.Range range = null;
25 Word.Table oTable = null;
26
27 創建一個空word文檔
45
46 添加標題文字
57
58 插入圖片
72
73 /// <summary>
74 /// 下標
75 /// </summary>
76 public void AddParagraph(string Str, float size, int bold, int Sub)
77 {
78 range = wDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
79 range.Text = Str;
80 range.Font.Size = size;//字體大小
81 range.Font.Bold = bold;//粗體
82 range.Font.Subscript = Sub;//是否爲下標1爲下標
83 range.Font.Color = Word.WdColor.wdColorBlack;//所選字體顏色
84 range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//設置段落居左
85 range.ParagraphFormat.LineSpacing = 2f;
86 }
87 /// <summary>
88 /// 所選字體顏色(紅色)
89 /// </summary>
90 public void AddTextColorRed(string Str, float size, int bold)
91 {
92 range = wDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
93 range.Text = Str;
94 range.Font.Size = size;//字體大小
95 range.Font.Bold = bold;//粗體
96 range.Font.Color = Word.WdColor.wdColorRed;//所選字體顏色
97 range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//設置段落居左
98 range.ParagraphFormat.LineSpacing = 2f;
99 }
100
101
102
103
104}
105
接下來添加一個Web項目,拖一個Button,在其.cs文件中寫入往word文檔輸入的內容,下面給出代碼:
此時就可以直接瀏覽頁面點擊按鈕,即可創建一個word文檔,
標題爲" 2008,中國加油",小二,加粗字體
內容爲
這樣就完成對word中寫入內容,還有其他的內容如插入圖片,表格(自己設計表格的樣式,合併單元格以及文字的
上下標等等,在以後分別介紹).