動態建立Word文檔
object path; //檔案路徑變數
MSWord.Application wordApp; //Word應用程式變數
MSWord.Document wordDoc; //Word文檔變數
path = @"C:\TeacherEmploy.doc"; //路徑
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,則刪除
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);
設定文檔寬度
wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2")); // 左邊緣距離
wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11;
wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2")); // 右邊緣距離
Object start = Type.Missing;
Object end = Type.Missing;
Object unit = Type.Missing;
Object count = Type.Missing;
wordDoc.Range(ref start, ref end).Delete(ref unit, ref count);
在文檔的第一行添加文本的時候,不要指定start和end的值,直接用預設的Nothing |
// 標題
string strTitle = "鹽城師範學院04-07學年專業技術人員聘期任務書";
wordDoc.Range(ref start, ref end).InsertBefore(strTitle);
// 標題樣式設定
wordDoc.Range(ref start, ref end).Font.Name = "Verdana";
wordDoc.Range(ref start, ref end).Font.Bold = 1;
wordDoc.Range(ref start, ref end).Font.Size = 17f;
wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment =
MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
// 添加表格
object location = strTitle.Length;
MSWord.Range range = wordDoc.Range(ref location, ref location);
MSWord.Table table = wordDoc.Tables.Add(range, 4, 2, ref Nothing, ref Nothing);
Tables是Word文檔中所有表格的集合,通過索引訪問每張表 |
// 表格樣式設定
wordDoc.Tables[1].Range.Font.Name = "仿宋";
wordDoc.Tables[1].Range.Font.Bold = 0;
wordDoc.Tables[1].Range.Font.Size = 12f;
wordDoc.Tables[1].Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
// 定位儲存格
Cell(i,j)實現定位儲存格(儲存格的索引如所示)
儲存格的合并與拆分
object Rownum = 1;
object Columnnum = 5;
table.Cell(1, 2).Split(ref Rownum, ref Columnnum); // 拆分
table.Cell(6,2).Merge(table.Cell(6,3)); // 合并
水平置中與垂直置中
table.Cell(8,1).Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter; // 垂直置中
table.Cell(8,1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; // 水平置中
儲存Word文檔與釋放資源
//WdSaveFormat為Word文檔的儲存格式
object format = MSWord.WdSaveFormat.wdFormatDocument;
//將wordDoc文檔對象的內容儲存為DOC文檔
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);
段落集合與表格集合
wordDoc.Paragraphs // 段落集合
wordDoc.Tables // 表格集合
如果直接在wordDoc.Paragraphs和wordDoc.Tables操作,則效果將反應在所有表格和所有段落中
通過索引可以訪問每一個段落和每一張表格,注意,索引是基於1的!