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

來源:互聯網
上載者:User
在網路上看到很多關於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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.