標籤:style blog http color os 檔案 io 資料
需要引用Office的DLL,在附件中
貼上核心代碼(轉載):
Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word._Document docFile = null; try { appWord.Visible = false; object objTrue = true; object objFalse = false; object objTemplate = Server.MapPath(@"dot//123.dot");//模板路徑 object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument; docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue); //第一步產生word文檔 //定義書籤變數 object obDD_Name = "DD_Name";//姓 名 object obDD_Sex = "DD_Sex";//性 別 object obDD_Age = "DD_Age";//年齡 object obDD_Birthday = "DD_Birthday"; //出生年月 object obDD_Nation = "DD_Nation"; //民 族 object obDD_Native = "DD_Native"; //籍 貫 //第二步 讀取資料,填充資料集 //SqlDataReader dr = XXXXX;//讀取出來的資料集 //第三步 給書籤賦值 //給書籤賦值 docFile.Bookmarks.get_Item(ref obDD_Name).Range.Text = "姓 名"; //姓 名 docFile.Bookmarks.get_Item(ref obDD_Sex).Range.Text = "性 別"; docFile.Bookmarks.get_Item(ref obDD_Age).Range.Text = "年齡"; //第四步 產生word DateTime dt = DateTime.Now; object filename = Server.MapPath("dot//") + "表" + dt.Ticks.ToString() + ".doc"; object miss = System.Reflection.Missing.Value; docFile.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); object missingValue = Type.Missing; object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue); appWord.Quit(ref miss, ref miss, ref miss); docFile = null; appWord = null; } catch (Exception ex) { //捕捉異常,如果出現異常則清空執行個體,退出word,同時釋放資源 string aa = e.ToString(); object miss = System.Reflection.Missing.Value; object missingValue = Type.Missing; object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue); appWord.Quit(ref miss, ref miss, ref miss); docFile = null; appWord = null; throw ex; }
服務端產生後,附加簡單的流下載代碼:
1 string fileName = "表.doc";//用戶端儲存的檔案名稱 2 string filePath = Server.MapPath("~/Download//Word//Table1.doc");//路徑 3 4 //以字元流的形式下載檔案 5 FileStream fs = new FileStream(filePath, FileMode.Open); 6 byte[] bytes = new byte[(int)fs.Length]; 7 fs.Read(bytes, 0, bytes.Length); 8 fs.Close(); 9 Response.ContentType = "application/octet-stream";10 //通知瀏覽器下載檔案而不是開啟11 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));12 Response.BinaryWrite(bytes);13 Response.Flush();14 Response.End();
附上各個Office版本Dll庫:
各個版本的microsoft.office.interop.word庫.rar