在醫療管理系統中為保存患者的體檢和治療記錄,方便以后的醫生或其他人查看。當把數據保存到數據庫中,需要新建很多的字段,而且操作很繁瑣,於是想到網頁的信息創建到一個word文本中,在顯示的時,可以在線打開word,也可以把word轉換成html標簽顯示。 這樣使用word代替網頁的原因有:
第一:網頁生成數學公式和特殊符號存儲和顯示比較麻煩(如何操作word生成數學公式,有待測試)
第二:生成Word版的報告更容易存檔和沒有環境下的傳閱及打印
第三:客戶直接操作Word感覺更親切,而且非常熟悉
Msdn上的word操作api(不過只有英文版,英文差的先閃過)
Word2007的API:http://msdn.microsoft.com/en-us/library/bb257531(v=office.12).aspx
Word2010的API:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(v=office.14).aspx
Word對象模型 (.Net Perspective)
五大對象
Application :代表Microsoft Word應用程序本身
是Document和Selection的基類。通過Application的屬性和方法,我們可以控制Word的大環境。
Document :代表一個Word文檔
當你新建一個Word文檔或者打開一個已有的Word文檔,你將創建一個Document對象,該對象被加入到Words Documents Collection中。擁有焦點的Document稱為ActiveDocument,可以通過Application對象的ActiveDocument屬性獲得當前文檔對象
Selection :代表當前選中的區域(高亮),沒有選中區域時代表光標點
它通常是高亮顯示的(例如,你要改變一段文字的字體,你首先得選中這段文字,那么選中的這塊區域就是當前文檔的Selection對象所包含的區域)
Bookmarks :書簽
1>書簽一般有名字
2>Saved with the document,且文檔關閉了之后書簽繼續存在
3>書簽通常是隱藏的,但也可以通過代碼設置其為可見
Range :代表一塊區域,與Selection類似,不過一般不可見
1>包含一個起始位置和一個結束位置
2>它可以包含光標點,一段文本或者整個文檔
3>它包含空格,tab以及paragraph marks
4>它可以是當前選中的區域,當然也可以不是當前選中區域
5>它被動態創建
6>當你在一個Range的末尾插入文本,這將擴展該Range
word文檔對象的結構圖
關於對象的詳細使用,可以參考msdn api
實例使用
創建Word 文檔所使用的主要方法是通過微軟公司提供的Microsoft Word X Object Library,
其中X 為版本號。Word2013為15.0 , Word2010對應14.0, Word 2007 對應12.0,Word 2003 對應11.0。
通過在項目中添加該組件,即可使用微軟公司提供的方法創建相應版本的Word 文檔。
在實例中我將所要生成word的格式設置為2003版本
新建一個winForm項目文件,
Com組件中添加 Microsoft Word 12.0 Object Library,引用面板中多出Microsoft.Office.Core、Microsoft.Office.Interop.Word兩個引用。
在類文件中添加應用如下:
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;
下面從word創建、格式設置、文本添加、圖片添加、表格添加展示部分代碼:

void CreateWord() { object path;//文件路徑 string strContent;//文件內容 MSWord.Application wordApp;//Word應用程序變量 MSWord.Document wordDoc;//Word文檔變量 path = "d:\\myWord.doc";//保存為Word2003文檔 // path = "d:\\myWord.doc";//保存為Word2007文檔 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } //由於使用的是COM 庫,因此有許多變量需要用Missing.Value 代替 Object Nothing = Missing.Value; //新建一個word對象 wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //WdSaveDocument為Word2003文檔的保存格式(文檔后綴.doc)\wdFormatDocumentDefault為Word2007的保存格式(文檔后綴.docx) object format = MSWord.WdSaveFormat.wdFormatDocument; //將wordDoc 文檔對象的內容保存為DOC 文檔,並保存到path指定的路徑 wordDoc.SaveAs(ref path, ref format, 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); Response.Write("<script>alert('" + path + ": Word文檔創建完畢!');</script>"); }

private void SetWordStyle() { object path;//文件路徑 string strContent;//文件內容 MSWord.Application wordApp;//Word應用程序變量 MSWord.Document wordDoc;//Word文檔變量 path = "d:\\myWord.doc";//保存為Word2003文檔 // path = "d:\\myWord.doc";//保存為Word2007文檔 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //頁面設置 wordDoc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;//設置紙張樣式 wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//排列方式為垂直方向 wordDoc.PageSetup.TopMargin = 57.0f; wordDoc.PageSetup.BottomMargin = 57.0f; wordDoc.PageSetup.LeftMargin = 57.0f; wordDoc.PageSetup.RightMargin = 57.0f; wordDoc.PageSetup.HeaderDistance = 30.0f;//頁眉位置 //設置頁眉 wordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;//視圖樣式 wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;//進入頁眉設置,其中頁眉邊距在頁面設置中已完成 wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //插入頁眉圖片(測試結果圖片未插入成功) wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; string headerfile = "d:\\header.jpg"; Microsoft.Office.Interop.Word.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing); shape1.Height = 20; shape1.Width = 80; wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(" 文檔頁眉"); //去掉頁眉的橫線 wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone; wordApp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false; wordApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;//退出頁眉設置 //為當前頁添加頁碼 Microsoft.Office.Interop.Word.PageNumbers pns = wordApp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//獲取當前頁的號碼 pns.NumberStyle = Microsoft.Office.Interop.Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash; pns.HeadingLevelForChapter = 0; pns.IncludeChapterNumber = false; pns.RestartNumberingAtSection = false; pns.StartingNumber = 0; object pagenmbetal = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;//將號碼設置在中間 object first = true; wordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first); object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, 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); Response.Write("<script>alert('" + path + ": Word文檔格式設置完畢!');</script>"); }
效果圖:

private void AddWordText() { object path;//文件路徑 string strContent;//文件內容 MSWord.Application wordApp;//Word應用程序變量 MSWord.Document wordDoc;//Word文檔變量 path = "d:\\myWord.doc";//保存為Word2003文檔 // path = "d:\\myWord.doc";//保存為Word2007文檔 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordApp.Selection.ParagraphFormat.LineSpacing = 35f;//設置文檔的行間距 //寫入普通文本 wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行縮進的長度 strContent = "c#向Word寫入文本 普通文本:\n"; wordDoc.Paragraphs.Last.Range.Text = strContent; //將文檔的前三個字替換成"asdfasdf",並將其顏色設為藍色 object start = 0; object end = 3; Microsoft.Office.Interop.Word.Range rang = wordDoc.Range(ref start, ref end); rang.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBrightGreen; rang.Text = "我是替換文字"; wordDoc.Range(ref start, ref end); //寫入黑體文本 object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory; wordApp.Selection.EndKey(ref unite, ref Nothing); wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行縮進的長度 strContent = "黑體文本\n ";//在文本中使用'\n'換行 wordDoc.Paragraphs.Last.Range.Font.Name = "黑體"; wordDoc.Paragraphs.Last.Range.Text = strContent; // wordApp.Selection.Text = strContent; //寫入加粗文本 strContent = "加粗文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Bold = 1;//Bold=0為不加粗 wordDoc.Paragraphs.Last.Range.Text = strContent; // wordApp.Selection.Text = strContent; //寫入15號字體文本 strContent = "15號字體文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Size = 15; wordDoc.Paragraphs.Last.Range.Text = strContent; //寫入斜體文本 strContent = "斜體文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Italic = 1; wordDoc.Paragraphs.Last.Range.Text = strContent; //寫入藍色文本 strContent = "藍色文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue; wordDoc.Paragraphs.Last.Range.Text = strContent; //寫入下划線文本 strContent = "下划線文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick; wordDoc.Paragraphs.Last.Range.Text = strContent; object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, 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); Response.Write("<script> alert('" + path + ": Word文檔寫入文本完畢!');</script>"); }
效果圖:

private void AddWordPic() { object path;//文件路徑 string strContent;//文件內容 MSWord.Application wordApp;//Word應用程序變量 MSWord.Document wordDoc;//Word文檔變量 path = "d:\\myWord.doc";//保存為Word2003文檔 // path = "d:\\myWord.doc";//保存為Word2007文檔 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); string filename = "d:\\kk.jpg"; //定義要向文檔中插入圖片的位置 object range = wordDoc.Paragraphs.Last.Range; //定義該圖片是否為外部鏈接 object linkToFile = false;//默認 //定義插入的圖片是否隨word一起保存 object saveWithDocument = true; //向word中寫入圖片 wordDoc.InlineShapes.AddPicture(filename, ref Nothing, ref Nothing, ref Nothing); object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory; wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中顯示圖片 wordDoc.InlineShapes[1].Height = 130; wordDoc.InlineShapes[1].Width = 200; wordDoc.Content.InsertAfter("\n"); wordApp.Selection.EndKey(ref unite, ref Nothing); wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; wordApp.Selection.Font.Size = 10;//字體大小 wordApp.Selection.TypeText("圖1 測試圖片\n"); object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, 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); Response.Write("<script>alert('" + path + ": Word文檔創建圖片完畢!');</script>"); }
效果圖:

private void AddWordTable() { object path;//文件路徑 string strContent;//文件內容 MSWord.Application wordApp;//Word應用程序變量 MSWord.Document wordDoc;//Word文檔變量 path = "d:\\myWord.doc";//保存為Word2003文檔 // path = "d:\\myWord.doc";//保存為Word2007文檔 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); int tableRow = 6; int tableColumn = 6; //定義一個word中的表格對象 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing); wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行"; for (int i = 1; i < tableRow; i++) { for (int j = 1; j < tableColumn; j++) { if (i == 1) { table.Cell(i, j+1).Range.Text = "Column " + j; } if (j == 1) { table.Cell(i+1, j).Range.Text = "Row " + i; } table.Cell(i+1, j+1).Range.Text = i + "行 " + j + "列"; } } //添加行 table.Rows.Add(ref Nothing); table.Rows[tableRow + 1].Height = 45; //向新添加的行的單元格中添加圖片 string FileName = "d:\\kk.jpg";//圖片所在路徑 object LinkToFile = false; object SaveWithDocument = true; object Anchor = table.Cell(tableRow+1, tableColumn).Range;//選中要添加圖片的單元格 wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 75;//圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 45;//圖片高度 // 將圖片設置為四周環繞型 MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare; //設置table樣式 table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast; table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size = 10.5F; table.Range.Font.Bold = 0; table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom; //設置table邊框樣式 table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble; table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; table.Rows[1].Range.Font.Bold = 1; table.Rows[1].Range.Font.Size = 12F; table.Cell(1, 1).Range.Font.Size = 10.5F; wordApp.Selection.Cells.Height = 40;//所有單元格的高度 for (int i = 2; i <= tableRow; i++) { table.Rows[i].Height = 20; } table.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; table.Columns[1].Width = 50; for (int i = 2; i <=tableColumn; i++) { table.Columns[i].Width = 75; } //添加表頭斜線,並設置表頭的樣式 table.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true; table.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGray60; table.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; //表格邊框 //表格內容行邊框 SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal, Microsoft.Office.Interop.Word.WdColor.wdColorGray20, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth025pt); //表格內容列邊框 SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical, Microsoft.Office.Interop.Word.WdColor.wdColorGray20, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth025pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); //合並單元格 table.Cell(4, 4).Merge(table.Cell(4, 5));//橫向合並 table.Cell(2, 3).Merge(table.Cell(4, 3));//縱向合並 object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, 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); Response.Write("<script>alert('" + path + ": Word文檔創建表格完畢!');</script>"); }
附:SetTableBorderStyle函數內容
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Word.WdColor.wdColorGreen; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt
效果圖:
書簽使用:
使用步驟:1:建立word模板,並且在word中插入要用到的書簽
2:c#方法中新建word操作類,並且打開硬盤中建立好的word模板
3:找到word模板中的書簽,並在書簽處寫入要插入的數據

public void AddDocModel() { killWinWordProcess(); wordApp = new ApplicationClass(); wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApp.Visible = false; object missing = System.Reflection.Missing.Value; object templateName = Application.StartupPath + @"\Report";//最終的word文檔需要寫入的位置 object ModelName = Application.StartupPath + @"\Report\ReportModel_Stand.doc";//word模板的位置 object count = 1; object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//換一行; wordDoc = wordApp.Documents.Open(ref ModelName, 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);//打開word模板 //在書簽處插入文字 object oStart = "PatName";//word中的書簽名 Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 range.Text = "這里是您要輸入的內容";//在書簽處插入文字內容 //在書簽處插入表格 oStart = "PatInfo";//word中的書簽名 range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 MSWord.Table tab_Pat = wordDoc.Tables.Add(range, 2, 4, ref missing, ref missing);//開辟一個2行4列的表格 tab_Pat.Range.Font.Size = 10.5F; tab_Pat.Range.Font.Bold = 0; tab_Pat.Columns[1].Width = 50; tab_Pat.Columns[2].Width = 65; tab_Pat.Columns[3].Width = 40; tab_Pat.Columns[4].Width = 40; tab_Pat.Cell(1, 1).Range.Text = "病歷號"; tab_Pat.Cell(1, 2).Range.Text = "PatientNO"; tab_Pat.Cell(1, 3).Range.Text = "身高"; tab_Pat.Cell(1, 4).Range.Text = "Height"; tab_Pat.Cell(2, 1).Range.Text = "姓名"; tab_Pat.Cell(2, 2).Range.Text ="PatientName"; tab_Pat.Cell(2, 3).Range.Text = "體重"; tab_Pat.Cell(2, 4).Range.Text = "Weight"; //保存word object format = WdSaveFormat.wdFormatDocument;//保存格式 wordDoc.SaveAs(ref templateName, ref format, 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); //關閉wordDoc,wordApp對象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); } // 殺掉winword.exe進程 public void killWinWordProcess() { System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD"); foreach (System.Diagnostics.Process process in processes) { bool b = process.MainWindowTitle == ""; if (process.MainWindowTitle == "") { process.Kill(); } } }
附: c# 將word文檔顯示在網頁上的方式:

public void WordToHtml(string wordFileName) { //在此處放置用戶代碼以初始化頁面 Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = word.GetType(); Documents docs = word.Documents; //打開文件 Type docsType = docs.GetType(); Document doc = (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true }); //轉換格式,另存為 Type docType = doc.GetType(); string wordSaveFileName = wordFileName.ToString(); //配置保存htm文件的地址 string strPath = Server.MapPath("~/Model/Word/Files/"); string strSaveFileName = strPath + "a.html"; //wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html"; object saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); //退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); Response.Write("<script language='javascript'>window.open ('Files/a.html', 'newwindow', 'height=600, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')</script>"); } Word轉換Html
轉換思路:
>取得Word文檔的本地路徑
>將Word文檔轉換為html文件
>將html保存到項目中
>在當前項目中打開此html文件
局限:
目前只在IE10測試中可以很好使用,在firefox和chrome測試用均有中文亂碼的問題,有待解決。
DEMOS
1. word 操作類庫參考類

sing System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.Word; using System.IO; using System.Web; using System.Data; using System.Reflection; using Microsoft.Win32; using System.Text.RegularExpressions; using System.Net; namespace OfficeOperate { public class WordOperate { #region 動態生成Word文檔並填充數據 /**//// <summary> /// 動態生成Word文檔並填充數據 /// </summary> /// <returns>返回自定義信息</returns> public static string CreateWordFile() { string message = ""; try { Object oMissing = System.Reflection.Missing.Value; string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在類庫添加using System.web的引用 if( !Directory.Exists( dir + "//file" ) ) { Directory.CreateDirectory( dir + "//file" ); //創建文件所在目錄 } string name = DateTime.Now.ToLongDateString() + ".doc"; object filename = dir + "//file//" + name; //文件保存路徑 //創建Word文檔 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); /**/////添加頁眉方法一: //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "無錫全真通科技有限公司" );//頁眉內容 //添加頁眉方法二: if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView ) { WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView; } WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; string sHeader = "頁眉內容"; WordApp.Selection.HeaderFooter.LinkToPrevious = false; WordApp.Selection.HeaderFooter.Range.Text = sHeader; WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//設置右對齊 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//設置左對齊 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁眉設置 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設置文檔的行間距 //移動焦點並換行 object count = 14; object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//換一行; WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移動焦點 WordApp.Selection.TypeParagraph();//插入段落 //文檔中創建表格 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing ); //設置表格樣式 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap; newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.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 = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 //填充表格內容 newTable.Cell( 2, 1 ).Range.Text = "產品基本信息"; newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//設置單元格內字體顏色 //合並單元格 newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) ); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //填充表格內容 newTable.Cell( 3, 1 ).Range.Text = "品牌名稱:"; newTable.Cell( 3, 2 ).Range.Text = "BrandName"; //縱向合並單元格 newTable.Cell( 3, 3 ).Select();//選中一行 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object moveCount = 5; object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend; WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend ); WordApp.Selection.Cells.Merge(); //插入圖片 if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) ) { string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.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;//圖片高度 } //將圖片設置為四周環繞型 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = Microsoft.Office.Interop.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 oMissing ); WordDoc.Paragraphs.Last.Range.Text = "文檔創建時間:" + DateTime.Now.ToString();//“落款” WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //文件保存 WordDoc.SaveAs( ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); WordDoc.Close( ref oMissing, ref oMissing, ref oMissing ); WordApp.Quit( ref oMissing, ref oMissing, ref oMissing ); message = name + "文檔生成成功"; } catch { message = "文件導出異常!"; } return message; } #endregion #region 創建並打開一個空的word文檔進行編輯 /**//// <summary> /// 創建並打開一個空的word文檔進行編輯 /// </summary> public static void OpenNewWordFileToEdit() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); } #endregion #region 創建word文檔 /**//// <summary> /// 創建word文檔 /// </summary> /// <returns></returns> public static string createWord() { Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Document WordDoc; string strContent = ""; object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " ); if( System.IO.File.Exists( (string)strFileName ) ) System.IO.File.Delete( (string)strFileName ); Object oMissing = System.Reflection.Missing.Value; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); #region 將數據庫中讀取得數據寫入到word文件中 strContent = "你好/n/n/r "; WordDoc.Paragraphs.Last.Range.Text = strContent; strContent = "這是測試程序 "; WordDoc.Paragraphs.Last.Range.Text = strContent; #endregion //將WordDoc文檔對象的內容保存為DOC文檔 WordDoc.SaveAs( ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); //關閉WordDoc文檔對象 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing ); //關閉WordApp組件對象 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing ); string message = strFileName + "/r/n " + "創建成功 "; return message; } #endregion #region 把Word文檔裝化為Html文件 /**//// <summary> /// 把Word文檔裝化為Html文件 /// </summary> /// <param name="strFileName">要轉換的Word文檔</param> public static void WordToHtml( string strFileName ) { string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html"; WordToHtml( strFileName, saveFileName ); } /**//// <summary> /// 把Word文檔裝化為Html文件 /// </summary> /// <param name="strFileName">要轉換的Word文檔</param> /// <param name="strSaveFileName">要生成的具體的Html頁面</param> public static void WordToHtml( string strFileName, string strSaveFileName ) { Microsoft.Office.Interop.Word.ApplicationClass WordApp; Microsoft.Office.Interop.Word.Document WordDoc; Object oMissing = System.Reflection.Missing.Value; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); object fileName = strFileName; WordDoc = WordApp.Documents.Open( ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); Type wordType = WordApp.GetType(); // 打開文件 Type docsType = WordApp.Documents.GetType(); // 轉換格式,另存為 Type docType = WordDoc.GetType(); object saveFileName = strSaveFileName; docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } ); #region 其它格式: /**//**/ /**////wdFormatHTML ///wdFormatDocument ///wdFormatDOSText ///wdFormatDOSTextLineBreaks ///wdFormatEncodedText ///wdFormatRTF ///wdFormatTemplate ///wdFormatText ///wdFormatTextLineBreaks ///wdFormatUnicodeText //-------------------------------------------------------------------------- // docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, // null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} ); // 退出 Word //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod, // null, WordApp, null ); #endregion WordDoc.Close( ref oMissing, ref oMissing, ref oMissing ); WordApp.Quit( ref oMissing, ref oMissing, ref oMissing ); } #endregion #region 導入模板 /**//// <summary> /// 導入模板 /// </summary> /// <param name="filePath">模板文檔路徑</param> public static void ImportTemplate( string filePath ) { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; object fileName = filePath; WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing ); } #endregion #region word中添加新表 /**//// <summary> /// word中添加新表 /// </summary> public static void AddTable() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end ); WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表 } #endregion #region 在表中插入新行 /**//// <summary> /// 在表中插入新的1行 /// </summary> public static void AddRow() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end ); WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add( ref beforeRow ); } #endregion #region 分離單元格 /**//// <summary> /// 合並單元格 /// </summary> public static void CombinationCell() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end ); WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add( ref beforeRow ); Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合並2行2列為一起 cell.Merge( newTable.Cell( 2, 2 ) ); //cell.Merge( newTable.Cell( 1, 3 ) ); } #endregion #region 分離單元格 /**//// <summary> /// 分離單元格 /// </summary> public static void SeparateCell() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end ); WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add( ref beforeRow ); Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 ); cell.Merge( newTable.Cell( 1, 2 ) ); object Rownum = 2; object Columnnum = 2; cell.Split( ref Rownum, ref Columnnum ); } #endregion #region 通過段落控制插入Insert a paragraph at the beginning of the document. /**//// <summary> /// 通過段落控制插入Insert a paragraph at the beginning of the document. /// </summary> public static void Insert() { object oMissing = System.Reflection.Missing.Value; //object oEndOfDoc = "//endofdoc"; /**//* /endofdoc is a predefined bookmark */ //Start Word and create a new document. Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); //Insert a paragraph at the beginning of the document. Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing ); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); } #endregion #region word文檔設置及獲取光標位置 /**//// <summary> /// word文檔設置及獲取光標位置 /// </summary> public static void WordSet() { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); #region 文檔格式設置 WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行編號 WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//頁面方向 WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上頁邊距 WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下頁邊距 WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左頁邊距 WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右頁邊距 WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//裝訂線位置 WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//頁眉 WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//頁腳 WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//紙張寬度 WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//紙張高度 WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源 WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源 WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//節的起始位置:新建頁 WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//頁眉頁腳-奇偶頁不同 WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//頁眉頁腳-首頁不同 WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//頁面垂直對齊方式 WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隱藏尾注 WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不設置首頁的內外邊距 WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不雙面打印 WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不設置手動雙面正面打印 WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不設置手動雙面背面打印 WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默認份數 WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//裝訂線位於左側 WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默認頁行數量 WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式為“只指定行網格” #endregion #region 段落格式設定 WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左縮進 WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右縮進 WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前間距 WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;// WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段后間距 WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;// WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//單倍行距 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端對齊 WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制 WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//與下段同頁 WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分頁 WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分頁 WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行號 WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字 WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行縮進 WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText; WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" ); WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" ); WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" ); WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" ); WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" ); WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1; WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0; WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1; WordApp.Selection.ParagraphFormat.WordWrap = 1; WordApp.Selection.ParagraphFormat.HangingPunctuation = 1; WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0; WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1; WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1; WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto; #endregion #region 字體格式設定 WordApp.Selection.Font.NameFarEast = "華文中宋"; WordApp.Selection.Font.NameAscii = "Times New Roman"; WordApp.Selection.Font.NameOther = "Times New Roman"; WordApp.Selection.Font.Name = "宋體"; WordApp.Selection.Font.Size = float.Parse( "14" ); WordApp.Selection.Font.Bold = 0; WordApp.Selection.Font.Italic = 0; WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone; WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WordApp.Selection.Font.StrikeThrough = 0;//刪除線 WordApp.Selection.Font.DoubleStrikeThrough = 0;//雙刪除線 WordApp.Selection.Font.Outline = 0;//空心 WordApp.Selection.Font.Emboss = 0;//陽文 WordApp.Selection.Font.Shadow = 0;//陰影 WordApp.Selection.Font.Hidden = 0;//隱藏文字 WordApp.Selection.Font.SmallCaps = 0;//小型大寫字母 WordApp.Selection.Font.AllCaps = 0;//全部大寫字母 WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WordApp.Selection.Font.Engrave = 0;//陰文 WordApp.Selection.Font.Superscript = 0;//上標 WordApp.Selection.Font.Subscript = 0;//下標 WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符間距 WordApp.Selection.Font.Scaling = 100;//字符縮放 WordApp.Selection.Font.Position = 0;//位置 WordApp.Selection.Font.Kerning = float.Parse( "1" );//字體間距調整 WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果 WordApp.Selection.Font.DisableCharacterSpaceGrid = false; WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone; #endregion #region 獲取光標位置 /**/////get_Information WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber ); //關於行號-頁號-列號-位置 //information 屬性 //返回有關指定的所選內容或區域的信息。variant 類型,只讀。 //expression.information(type) //expression 必需。該表達式返回一個 range 或 selection 對象。 //type long 類型,必需。需要返回的信息。可取下列 wdinformation 常量之一: //wdactiveendadjustedpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾。如果設置了一個起始頁碼,並對頁碼進行了手工調整,則返回調整過的頁碼。 //wdactiveendpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾,頁碼從文檔的開頭開始計算而不考慮對頁碼的任何手工調整。 //wdactiveendsectionnumber 返回節號,在該節中包含了指定的所選內容或區域的活動結尾。 //wdatendofrowmarker 如果指定的所選內容或區域位於表格的行結尾標記處,則本參數返回 true。 //wdcapslock 如果大寫字母鎖定模式有效,則本參數返回 true。 //wdendofrangecolumnnumber 返回表格列號,在該表格列中包含了指定的所選內容或區域的活動結尾。 //wdendofrangerownumber 返回表格行號,在該表格行包含了指定的所選內容或區域的活動結尾。 //wdfirstcharactercolumnnumber 返回指定的所選內容或區域中第一個字符的位置。如果所選內容或區域是折疊的,則返回所選內容或區域右側緊接着的字符編號。 //wdfirstcharacterlinenumber 返回所選內容中第一個字符的行號。如果 pagination 屬性為 false,或 draft 屬性為 true,則返回 - 1。 //wdframeisselected 如果所選內容或區域是一個完整的圖文框文本框,則本參數返回 true。 //wdheaderfootertype 返回一個值,該值表明包含了指定的所選內容或區域的頁眉或頁腳的類型,如下表所示。 值 頁眉或頁腳的類型 //- 1 無 //0 偶數頁頁眉 //1 奇數頁頁眉 //2 偶數頁頁腳 //3 奇數頁頁腳 //4 第一個頁眉 //5 第一個頁腳 //wdhorizontalpositionrelativetopage 返回指定的所選內容或區域的水平位置。該位置是所選內容或區域的左邊與頁面的左邊之間的距離,以磅為單位。如果所選內容或區域不可見,則返回 - 1。 //wdhorizontalpositionrelativetotextboundary 返回指定的所選內容或區域相對於周圍最近的正文邊界的左邊的水平位置,以磅為單位。如果所選內容或區域沒有顯示在當前屏幕,則本參數返回 - 1。 //wdinclipboard 有關此常量的詳細內容,請參閱 microsoft office 98 macintosh 版的語言參考幫助。 //wdincommentpane 如果指定的所選內容或區域位於批注窗格,則返回 true。 //wdinendnote 如果指定的所選內容或區域位於頁面視圖的尾注區內,或者位於普通視圖的尾注窗格中,則本參數返回 true。 //wdinfootnote 如果指定的所選內容或區域位於頁面視圖的腳注區內,或者位於普通視圖的腳注窗格中,則本參數返回 true。 //wdinfootnoteendnotepane 如果指定的所選內容或區域位於頁面視圖的腳注或尾注區內,或者位於普通視圖的腳注或尾注窗格中,則本參數返回 true。詳細內容,請參閱前面的 wdinfootnote 和 wdinendnote 的說明。 //wdinheaderfooter 如果指定的所選內容或區域位於頁眉或頁腳窗格中,或者位於頁面視圖的頁眉或頁腳中,則本參數返回 true。 //wdinmasterdocument 如果指定的所選內容或區域位於主控文檔中,則本參數返回 true。 //wdinwordmail 返回一個值,該值表明了所選內容或區域的的位置,如下表所示。值 位置 //0 所選內容或區域不在一條電子郵件消息中。 //1 所選內容或區域位於正在發送的電子郵件中。 //2 所選內容或區域位於正在閱讀的電子郵件中。 //wdmaximumnumberofcolumns 返回所選內容或區域中任何行的最大表格列數。 //wdmaximumnumberofrows 返回指定的所選內容或區域中表格的最大行數。 //wdnumberofpagesindocument 返回與所選內容或區域相關聯的文檔的頁數。 //wdnumlock 如果 num lock 有效,則本參數返回 true。 //wdovertype 如果改寫模式有效,則本參數返回 true。可用 overtype 屬性改變改寫模式的狀態。 //wdreferenceoftype 返回一個值,該值表明所選內容相對於腳注、尾注或批注引用的位置,如下表所示。 值 描述 //— 1 所選內容或區域包含、但不只限定於腳注、尾注或批注引用中。 //0 所選內容或區域不在腳注、尾注或批注引用之前。 //1 所選內容或區域位於腳注引用之前。 //2 所選內容或區域位於尾注引用之前。 //3 所選內容或區域位於批注引用之前。 //wdrevisionmarking 如果修訂功能處於活動狀態,則本參數返回 true。 //wdselectionmode 返回一個值,該值表明當前的選定模式,如下表所示。 值 選定模式 //0 常規選定 //1 擴展選定 //2 列選定 //wdstartofrangecolumnnumber 返回所選內容或區域的起點所在的表格的列號。 //wdstartofrangerownumber 返回所選內容或區域的起點所在的表格的行號。 //wdverticalpositionrelativetopage 返回所選內容或區域的垂直位置,即所選內容的上邊與頁面的上邊之間的距離,以磅為單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。 //wdverticalpositionrelativetotextboundary 返回所選內容或區域相對於周圍最近的正文邊界的上邊的垂直位置,以磅為單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。 //wdwithintable 如果所選內容位於一個表格中,則本參數返回 true。 //wdzoompercentage 返回由 percentage 屬性設置的當前的放大百分比。 #endregion #region 光標移動 //移動光標 //光標下移3行 上移3行 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object count = 3; WordApp.Selection.MoveEnd( ref unit, ref count ); WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing ); //Microsoft.Office.Interop.Word.WdUnits說明 //wdCell A cell. //wdCharacter A character. //wdCharacterFormatting Character formatting. //wdColumn A column. //wdItem The selected item. //wdLine A line. //行 //wdParagraph A paragraph. //wdParagraphFormatting Paragraph formatting. //wdRow A row. //wdScreen The screen dimensions. //wdSection A section. //wdSentence A sentence. //wdStory A story. //wdTable A table. //wdWindow A window. //wdWord A word. //錄制的vb宏 // ,移動光標至當前行首 // Selection.HomeKey unit:=wdLine // '移動光標至當前行尾 // Selection.EndKey unit:=wdLine // '選擇從光標至當前行首的內容 // Selection.HomeKey unit:=wdLine, Extend:=wdExtend // '選擇從光標至當前行尾的內容 // Selection.EndKey unit:=wdLine, Extend:=wdExtend // '選擇當前行 // Selection.HomeKey unit:=wdLine // Selection.EndKey unit:=wdLine, Extend:=wdExtend // '移動光標至文檔開始 // Selection.HomeKey unit:=wdStory // '移動光標至文檔結尾 // Selection.EndKey unit:=wdStory // '選擇從光標至文檔開始的內容 // Selection.HomeKey unit:=wdStory, Extend:=wdExtend // '選擇從光標至文檔結尾的內容 // Selection.EndKey unit:=wdStory, Extend:=wdExtend // '選擇文檔全部內容(從WholeStory可猜出Story應是當前文檔的意思) // Selection.WholeStory // '移動光標至當前段落的開始 // Selection.MoveUp unit:=wdParagraph // '移動光標至當前段落的結尾 // Selection.MoveDown unit:=wdParagraph // '選擇從光標至當前段落開始的內容 // Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend // '選擇從光標至當前段落結尾的內容 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // '選擇光標所在段落的內容 // Selection.MoveUp unit:=wdParagraph // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // '顯示選擇區的開始與結束的位置,注意:文檔第1個字符的位置是0 // MsgBox ("第" & Selection.Start & "個字符至第" & Selection.End & "個字符") // '刪除當前行 // Selection.HomeKey unit:=wdLine // Selection.EndKey unit:=wdLine, Extend:=wdExtend // Selection.Delete // '刪除當前段落 // Selection.MoveUp unit:=wdParagraph // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // Selection.Delete //表格的光標移動 //光標到當前光標所在表格的地單元格 WordApp.Selection.Tables[1].Cell( 1, 1 ).Select(); //unit對象定義 object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式 object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend對光標移動區域進行擴展選擇 object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文檔行方式,可以看成表格一行.不過和wdRow有區別 object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,對於表格可以選擇到表格行后的換車符,對於跨行合並的行選擇,我能找到的最簡單方式 //object count = 1;//光標移動量 #endregion } #endregion #region 讀取Word表格中某個單元格的數據。其中的參數分別為文件名(包括路徑),行號,列號。 /**//// <summary> /// 讀取Word表格中某個單元格的數據。其中的參數分別為文件名(包括路徑),行號,列號。 /// </summary> /// <param name="fileName">word文檔</param> /// <param name="rowIndex">行</param> /// <param name="colIndex">列</param> /// <returns>返回數據</returns> public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex ) { ApplicationClass cls = null; Document doc = null; Table table = null; object missing = Missing.Value; object path = fileName; cls = new ApplicationClass(); try { doc = cls.Documents.Open ( ref path, 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 ); table = doc.Tables[1]; string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString(); text = text.Substring( 0, text.Length - 2 ); //去除尾部的mark return text; } catch( Exception ex ) { return ex.Message; } finally { if( doc != null ) doc.Close( ref missing, ref missing, ref missing ); cls.Quit( ref missing, ref missing, ref missing ); } } #endregion #region 修改word表格中指定單元格的數據 /**//// <summary> /// 修改word表格中指定單元格的數據 /// </summary> /// <param name="fileName">word文檔包括路徑</param> /// <param name="rowIndex">行</param> /// <param name="colIndex">列</param> /// <param name="content"></param> /// <returns></returns> public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content ) { ApplicationClass cls = null; Document doc = null; Table table = null; object missing = Missing.Value; object path = fileName; cls = new ApplicationClass(); try { doc = cls.Documents.Open ( ref path, 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 ); table = doc.Tables[1]; //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回車 table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content; return true; } catch { return false; } finally { if( doc != null ) { doc.Close( ref missing, ref missing, ref missing ); cls.Quit( ref missing, ref missing, ref missing ); } } } #endregion #region 清楚word進程 /**//// <summary> /// 清楚word進程 /// </summary> public static void KillWordProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses(); foreach( System.Diagnostics.Process p in myPs ) { if( p.Id != 0 ) { string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString(); try { if( p.Modules != null ) if( p.Modules.Count > 0 ) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS += "/n Modules[0].FileName:" + pm.FileName; myS += "/n Modules[0].ModuleName:" + pm.ModuleName; myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString(); if( pm.ModuleName.ToLower() == "winword.exe" ) p.Kill(); } } catch { } finally { } } } } #endregion #region 清楚excel進程 /**//// <summary> /// 清楚excel進程 /// </summary> public static void KillExcelProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses(); foreach( System.Diagnostics.Process p in myPs ) { if( p.Id != 0 ) { string myS = "excel.EXE" + p.ProcessName + " ID:" + p.Id.ToString(); try { if( p.Modules != null ) if( p.Modules.Count > 0 ) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS += "/n Modules[0].FileName:" + pm.FileName; myS += "/n Modules[0].ModuleName:" + pm.ModuleName; myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString(); if( pm.ModuleName.ToLower() == "excel.exe" ) p.Kill(); } } catch { } finally { } } } } #endregion #region 網頁內容或導入word或excel /**//// <summary> /// 網頁內容保存或導出為word或excel /// </summary> /// <param name="url">網頁地址</param> /// <param name="num">0為導出word,1為導出excel</param> public static void SaveOrOutData( string url, int num )//導出數據的函數0為word,1為Excel { WebRequest req = WebRequest.Create( url ); WebResponse resp = req.GetResponse(); StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 ); string x = sr.ReadToEnd(); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" ); string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" ); if( num == 0 ) { fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc"; System.Web.HttpContext.Current.Response.ContentType = "application/ms-word"; } else { fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls"; System.Web.HttpContext.Current.Response.ContentType = "application nd.xls"; } System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName ); System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//獲取table標簽 System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } /**//// <summary> /// 獲取網頁table標簽的內容 /// </summary> /// <param name="input">html代碼</param> /// <returns></returns> private static string getBodyContent( string input ) { string pattern = @"<table.*?</table>"; Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase ); Match mc = reg.Match( input ); string bodyContent = ""; if( mc.Success ) { bodyContent = mc.Value; } return bodyContent; } #endregion #region 判斷系統是否裝excel /**//// <summary> /// 判斷系統是否裝excel /// </summary> /// <returns></returns> public static bool IsInstallExcel() { RegistryKey machineKey = Registry.LocalMachine; if( IsInstallExcelByVersion( "12.0", machineKey ) ) { return true; } if( IsInstallExcelByVersion( "11.0", machineKey ) ) { return true; } return false; } /**//// <summary> /// 判斷系統是否裝某版本的excel /// </summary> /// <param name="strVersion">版本號</param> /// <param name="machineKey"></param> /// <returns></returns> private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey ) { try { RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" ); if( installKey == null ) { return false; } return true; } catch { return false; } } #endregion #region 判斷系統是否裝word /**//// <summary> /// 判斷系統是否裝word /// </summary> /// <returns></returns> public static bool IsInstallWord() { RegistryKey machineKey = Registry.LocalMachine; if( IsInstallExcelByVersion( "12.0", machineKey ) ) { return true; } if( IsInstallExcelByVersion( "11.0", machineKey ) ) { return true; } return false; } /**//// <summary> /// 判斷系統是否裝某版本的word /// </summary> /// <param name="strVersion">版本號</param> /// <param name="machineKey"></param> /// <returns></returns> private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey ) { try { RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" ); if( installKey == null ) { return false; } return true; } catch { return false; } } #endregion } }
引用:
http://blog.csdn.net/ruby97/article/details/7406806