Asp.net操作Word文檔,原來這么簡單啊!


引用Word對象庫文件
 

具體做法是打開菜單欄中的項目>添加引用>瀏覽,在打開的“選擇組件”對話框中找到MSWORD.OLB后按確定即可引入此對象庫文件,vs.net將會自動將庫文件轉化為DLL組件,這樣我們只要在源碼中創建該組件對象即可達到操作Word的目的!
 

如圖

 

這會自動在你的應用程序文件夾中放置一個程序集(assembly)將COM接口邦定到Word。
 

 

上傳並存儲word文件

上傳文件時首先通過上傳控件找到所需上傳的文件,然后獲取文件的大小,最后以流的形式寫入數據庫

 

具體代碼為

 
C# 代碼    復制
 private void Btn_OK_Click(object sender, System.EventArgs e)   {   string name=name_TextBox.Text;   //接收上傳文件    Stream fileStream=File1.PostedFile.InputStream;   //獲取上傳文件字節的大小    int length=File1.PostedFile.ContentLength;   byte[] wordData=new byte[length];   //從流中讀取字節並寫入wordData    int n=fileStream.Read(wordData,0,length);   //獲取當前時間    DateTime time=DateTime.Now;   //連接數據庫    SqlConnection conn=new SqlConnection();   conn.ConnectionString="workstation id=TIANCHUNZHU;packet size=4096;integrated security=SSPI;data source=TIANCHUNZHU;persist security info=False;initial catalog=test";   SqlCommand cmd=new SqlCommand();   cmd.Connection=conn;   cmd.CommandText="INSERT INTO word (fileName,postTime,fileContent) values (@fileName,@postTime,@fileContent)";   SqlParameter nameParam=new SqlParameter("@fileName",System.Data.SqlDbType.VarChar,50);   nameParam.Value=name;   cmd.Parameters.Add(nameParam);   SqlParameter timeParam=new SqlParameter("@postTime",System.Data.SqlDbType.DateTime,8);   timeParam.Value=time;   cmd.Parameters.Add(timeParam);  //添加word文件    SqlParameter contentParam=new SqlParameter("@fileContent",System.Data.SqlDbType.Image); ①//見本段最后注解    contentParam.Value=wordData;   cmd.Parameters.Add(contentParam);   conn.Open();   cmd.ExecuteNonQuery();   conn.Close();   } 

 

說明

此處由於是Image類型文件,事先可能無法預測文件的大小,因此可不必指定size參數。如果希望控制上傳文件的大小則可以輸入size參數。如指定1000,則上傳時最大可以上傳1k的word文檔。

 

從數據庫中讀取數據並恢復為word文件

 

讀取數據時先將數據從數據庫中讀入緩沖區,然后再從緩沖區寫入最終文件。因此首先要開辟一個緩沖區並設定它的大小,每當緩沖區讀滿時就要將緩沖區內的數據寫入文件,以清空緩沖區並繼續向緩沖區讀數據,直到最后一次將緩沖區內剩余的數據全部寫入文件,新的word文檔即可生成。

由於這一部分用到了字節流的輸入輸出操作,因此要引用System.IO命名空間

 

代碼

 
C# 代碼    復制
 private void Btn_get_Click(object sender, System.EventArgs e)  {  //連接數據庫    SqlConnection conn=new SqlConnection();   conn.ConnectionString="workstation id=TIANCHUNZHU;packet size=4096;integrated security=SSPI;data source=TIANCHUNZHU;persist security info=False;initial catalog=test";   SqlCommand cmd=new SqlCommand();   cmd.Connection=conn;   //根據TextBox中指定的文件名進行查找讀取    cmd.CommandText="select fileContent from word where fileName='"+name_TextBox.Text.ToString()+"'";   FileStream fs;   BinaryWriter bw;   //設定允許讀取到緩沖區的最大長度    int buffersize=100;   //要將字節流讀入的緩沖區    byte[] outbyte=new byte[buffersize];   //用於記錄已經讀取的字節數    long reval;   //字段中的索引,從這里開始讀取操作    long startIndex;   //FileStream對象將封裝的文件的相對路徑或絕對路徑    string filePath=@"C:wordData.doc";   conn.Open();   SqlDataReader reader;   reader=cmd.ExecuteReader();   while (reader.Read())   {   fs=new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.Write);   bw=new BinaryWriter(fs);   startIndex=0;   //將字節流讀入outbyte緩沖區中並返回讀取的字節數    reval=reader.GetBytes(0,startIndex,outbyte,0,buffersize);   //當讀取的字節流達到緩沖區允許的最大長度時要卸載緩沖區內的數據並將數據寫入文件    while (reval==buffersize)   {   bw.Write(outbyte);   bw.Flush();   //重新設定開始讀取的位置,並繼續讀取和寫數據    startIndex+=buffersize;   reval=reader.GetBytes(0,startIndex,outbyte,0,buffersize);   }   //將緩沖區內最后剩余的數據寫入文件    bw.Write(outbyte,0,(int)reval-1);   bw.Flush();   bw.Close();   fs.Close();   }   reader.Close();   conn.Close();  } 

 

說明

此時將按照filePath中指定的路徑和名稱重新生成word文檔。可以在filePath中根據具體情況指定生成的word文檔的名稱和路徑。

 

常用生成word文檔的代碼

 
C# 代碼    復制
 public string CreateWordFile(string CheckedInfo) { string message = ""; try { Object Nothing = System.Reflection.Missing.Value; Directory.CreateDirectory("C:/CNSI"); //創建文件所在目錄 string name = "CNSI.doc"; object filename = "C://CNSI//" + name; //文件保存路徑 //創建Word文檔 Word.Application WordApp = new Word.ApplicationClass(); Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);   //添加頁眉 WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[頁眉內容]"); WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//設置右對齊 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁眉設置  WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設置文檔的行間距  /*WordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; //設置頁面為縱向  WordDoc.PageSetup.PageHeight = WordApp.CentimetersToPoints(21F);  WordDoc.PageSetup.PageWidth = WordApp.CentimetersToPoints(29.7F);  WordDoc.PageSetup.TopMargin = 57; //設置上邊距  WordDoc.PageSetup.BottomMargin = 57;//設置下邊距  WordDoc.PageSetup.LeftMargin = 57;//設置左邊距  WordDoc.PageSetup.RightMargin = 57;//設置右邊距*/  //移動焦點並換行 object count = 14; object WdLine = Word.WdUnits.wdLine;//換一行; WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動焦點 WordApp.Selection.TypeParagraph();//插入段落  //文檔中創建表格 Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing); //設置表格樣式 newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap; newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; newTable.Columns[1].Width = 100f; newTable.Columns[2].Width = 220f; newTable.Columns[3].Width = 105f;  //填充表格內容 newTable.Cell(1, 1).Range.Text = "產品詳細信息表"; newTable.Cell(1, 1).Range.Bold = 2;//設置單元格中字體為粗體 //合並單元格 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3)); WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中   //填充表格內容 newTable.Cell(2, 1).Range.Text = "產品基本信息"; newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//設置單元格內字體顏色 //合並單元格 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3)); WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;   //填充表格內容 newTable.Cell(3, 1).Range.Text = "品牌名稱:"; newTable.Cell(3, 2).Range.Text = CheckedInfo; //縱向合並單元格 newTable.Cell(3, 3).Select();//選中一行 object moveUnit = Word.WdUnits.wdLine; object moveCount = 5; object moveExtend = Word.WdMovementType.wdExtend; WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend); WordApp.Selection.Cells.Merge(); //插入圖片 string FileName = @"C:\\1.jpg";//圖片所在路徑 object LinkToFile = false; object SaveWithDocument = true; object Anchor = WordDoc.Application.Selection.Range; WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//圖片寬度 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//圖片高度 //將圖片設置為四周環繞型 Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;  newTable.Cell(12, 1).Range.Text = "產品特殊屬性"; newTable.Cell(12, 1).Merge(newTable.Cell(12, 3)); //在表格中增加行 WordDoc.Content.Tables[1].Rows.Add(ref Nothing);   WordDoc.Paragraphs.Last.Range.Text = "文檔創建時間:" + DateTime.Now.ToString();//“落款” WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;   //文件保存 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.Close(ref Nothing, ref Nothing, ref Nothing); WordApp.Quit(ref Nothing, ref Nothing, ref Nothing); message = name + "文檔生成成功,以保存到C:CNSI下"; } catch { message = "文件導出異常!"; } return message; } 

 

有幾點需要注意的地方如下:

1、在調整合並后的單元格中的內容的位置時,原先我是先向單元格中寫數據,然后選中單元格,再合並單元格,最后調整水平和垂直位置。但是結果發現,不管我怎么調位置,單元格的內容始終都顯示在最下方。經過一番嘗試后,我發現應該先合並單元格,再往合並后的單元格中添加數據,然后選中合並后的單元格,最后設置水平位置和垂直位置。這樣才可行。舉例如下:

newTable.Cell(12, 1).Merge(newTable.Cell(18, 1));
newTable.Cell(12, 1).Range.Text = "范例";
newTable.Cell(12, 1).Select();
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中

 

2、網站發布前,Word導出正常,但發布之后就Word導出異常,則可能是權限的問題,最簡單的解決辦法是在<system.web></system.web>之間添加如下語句:

<identity impersonate="true" userName="你自己的賬戶" password="密碼"/>,注意密碼不能為空或者是弱密碼。

 

 

3、如果出現如下錯誤:

 

 

"word 無法保存此文件, 因為它已在別處打開。(C:\...\STARTUP\Powerword.dot)"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM