[ASP.NET]使用ASP.NET產生Word並直接下載

  • 12387
  • 0

摘要:[ASP.NET]使用ASP.NET產生Word並直接下載

步驟1.

加入參考 Microsoft.Office.Interop.Word

步驟2.

選寫產生Word的頁面

程式碼:

ApplicationClass wordApp = new ApplicationClass();
object missing = System.Reflection.Missing.Value;
object tempName = @"C:\Temp.dot";//word範本檔案
object docName = @"C:\a.doc";//要儲存的檔案名稱
Document MyDoc = wordApp.Documents.Add(ref tempName, ref missing, ref missing, ref missing);
wordApp.Visible = true;
MyDoc.Activate();
wordApp.Selection.Font.Size = 30; // 字體大小
wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; //置中
wordApp.Selection.Font.Bold = (int)WdConstants.wdToggle;//設定為粗體
wordApp.Selection.TypeText("hello");//寫入hello
//另存新檔
MyDoc.SaveAs(ref docName, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
//另存新檔結束
MyDoc.Close(ref missing, ref missing, ref missing);//關閉
wordApp.Quit(ref missing, ref missing, ref missing);//結束word程式
MyDoc = null;
wordApp = null;
Response.Redirect("DownloadWord.aspx?id=" + "a.doc");//將檔案名稱傳送到另一個頁面

步驟3.

下載頁面:

程式碼:

FileInfo DownloadFile = new FileInfo(@"C:\" + FullFileName);
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
//Response.ContentType指定檔案類型 
//可以為application/ms-excel || application/ms-word || application/ms-txt 
//application/ms-html || 或其他瀏覽器可以支援的文件
Response.ContentType = "application/octet-stream";//所有類型
//下面這行很重要, attachment 参数表示作為附件下載,可以改成 online線上開啟
//filename=FileFlow.xls 指定输出檔案名稱,注意其附檔名和指定檔案類型相符,
//可以為:.doc || .xls || .txt ||.htm
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(FullFileName, System.Text.Encoding.UTF8));   
Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());//取得檔案大小

Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();

========================================================================================

●必須先用Word另存一個*.dot的範本來讓產生word的頁面抓取並修改範本內內容並另存新的Word檔

●若是在用戶端必須加入權限否則會出現錯誤可以參考

[ASP.NET]asp.net 存取 word 權限問題

範例:donwloadFile.rar

我只是個小小的入門者