引用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));