程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> ASP.NET2.0導出Word文檔(C#導出DOC)

ASP.NET2.0導出Word文檔(C#導出DOC)

編輯:C#入門知識

在網絡上看到很多關於ASP.NET導出DOC文檔的例子,有的干脆就直接將html頁面不做任何處理直接導出為DOC文件,但是那樣會有很多錯誤,例如將某些控件顯示為圖片。我還曾經見過微軟為中國某個大公司制作的一個XX系統,導出的DOC文件實際上是某種特殊格式的XML,但是對於這個技術我還不是很了解。於是我在網絡上收集資料,找到很多種實現方法,一一實驗,最後總結出以下經驗。

一、首先配置系統環境:

1、在命令行(work 的sdk命令行提示)中輸入:dcomcnfg,會顯示出“組件服務”管理器
2、打開“組件服務-》計算機-》我的電腦-》DCOM 配置”,找到“Microsoft Word文檔”,單擊右鍵,選擇“屬性”
3、在“屬性”對話框中單擊“安全”選項卡,在“啟動和激活權限”處選擇“自定義”,再單擊右邊的”編輯“,在彈出的對話框中添加”ASPNET
“(在IIS6中是NETWORD SERVICE)用戶,給予”本地啟動“和”本地激活“的權限,單擊”確定“,關閉”組件服務“管理器。
這樣就能在Asp.net頁面中訪問Word對象了。

二、修改WEB.CONFIG,在<system.web>區段內加入:<identity impersonate="true"/>

三、添加引用:《網站》——>《添加引用》——>《COM》——Microsoft Word 11.0 Object Library

四、添加命名空間引用,
using Microsoft.Office.Interop.Word;

五:代碼
Object Nothing = System.Reflection.Missing.Value;
//取得Word文件保存路徑
object filename = "c:aa.doc";
//創建一個名為WordApp的組件對象
Microsoft.Office.Interop.Word.Application WordApp = new ApplicationClass();
//網絡上有寫代碼中直接使用Word.Application WordApp = new ApplicationClass(); 但我在實際編寫中總是出現錯誤。
//創建一個名為WordDoc的文檔對象
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//增加一表格
Microsoft.Office.Interop.Word.Table table = WordDoc.Tables.Add(WordApp.Selection.Range, 3, 3, ref Nothing, ref Nothing);
//在表格第一單元格中添加自定義的文字內容
table.Cell(1, 1).Range.Text = "lllll";
//在文檔空白地方添加文字內容
WordDoc.Paragraphs.Last.Range.Text = "Wellcome To Aspxcn.Com";
//將WordDoc文檔對象的內容保存為DOC文檔
WordDoc.SaveAs(ref filename, 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文檔對象
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//關閉WordApp組件對象
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
 

    

  1. 上一頁:
  2. 下一頁: