熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#操作Word文檔(Office 2007)

2022-06-13   來源: .NET編程 
    首先引入類庫MicrosoftOfficeInteropWord然後進行編程代碼如下
  
  using System;
  using SystemCollectionsGeneric;
  using SystemComponentModel;
  using SystemData;
  using SystemDrawing;
  using SystemText;
  using SystemWindowsForms;
  using MicrosoftOfficeInteropWord;
  
  namespace WordTest
  {
   public partial class Form : Form
   {
   object strFileName;
   Object Nothing;
   MicrosoftOfficeInteropWordApplication myWordApp = new MicrosoftOfficeInteropWordApplicationClass();
   Document myWordDoc;
   string strContent = ;
  
   public Form()
   {
   InitializeComponent();
   }
  
   private void button_Click(object sender EventArgs e)
   {
   createWord();
   //openWord();
   }
  
   private void createWord()
   {
   strFileName = SystemWindowsFormsApplicationStartupPath + testdoc;
   if (SystemIOFileExists((string)strFileName))
   SystemIOFileDelete((string)strFileName);
   Object Nothing = SystemReflectionMissingValue;
   myWordDoc = myWordAppDocumentsAdd(ref Nothing ref Nothing ref Nothing ref Nothing);
  
   #region 將數據庫中讀取得數據寫入到word文件中
  
   strContent = 你好\n\n\r;
   myWordDocParagraphsLastRangeText = strContent;
  
   strContent = 這是測試程序;
   myWordDocParagraphsLastRangeText = strContent;
  
  
   #endregion
  
   //將WordDoc文檔對象的內容保存為DOC文檔
   myWordDocSaveAs(ref strFileName 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 ref Nothing);
   //關閉WordDoc文檔對象
   myWordDocClose(ref Nothing ref Nothing ref Nothing);
   //關閉WordApp組件對象
   myWordAppQuit(ref Nothing ref Nothing ref Nothing);
  
   thisrichTextBoxText = strFileName + \r\n + 創建成功;
  
   }
   private void openWord()
   {
   fontDialogShowDialog();
   SystemDrawingFont font = fontDialogFont;
   object filepath = D:\\aspdocx;
   object oMissing = SystemReflectionMissingValue;
   myWordDoc = myWordAppDocumentsOpen(ref filepath ref oMissing ref oMissing ref oMissing ref oMissing
   ref oMissing ref oMissing ref oMissing ref oMissing ref oMissing ref oMissing
   ref oMissing ref oMissing ref oMissing ref oMissing ref oMissing);
   myWordDocContentFontSize = fontSize;
   myWordDocContentFontName = fontName;
   myWordDocSave();
   richTextBoxText = myWordDocContentText;
  
  
   myWordDocClose(ref oMissing ref oMissing ref oMissing);
   myWordAppQuit(ref oMissing ref oMissing ref oMissing);
   }
  
  }
  
  

From:http://tw.wingwit.com/Article/program/net/201311/12464.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.