C# Word


C# 操作word文檔

1.c#操作word 在指定書簽插入文字或者圖片


 1using Word = Microsoft.Office.Interop.Word;
 2
 3object Nothing = System.Reflection.Missing.Value;
 4         object format = Word.WdSaveFormat.wdFormatDocument;
 5         Word.Application wordApp = new Word.ApplicationClass();
 6         //打開網頁選擇內容
 7         object srcFileName = @"c:\new1.doc"; //里面有圖片
 8          Word.Document wordDoc2 = wordApp.Documents.Open(ref srcFileName, 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);
 9            try
10         {
11             object bookmarkName = "jlr";
12             //Word.Range rng = wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range;
13             //rng.Text = "newText";
14             //object range = rng;
15             //wordDoc2.Bookmarks.Add("jlr", ref range);
16             wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();
17             wordApp.Selection.InlineShapes.AddPicture("c:\\1.jpg", ref Nothing, ref Nothing, ref Nothing);
18             wordDoc2.Save();
19
20         }
21         catch { }
22         finally
23         {
24             //關閉網頁wordDoc2
25             wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);
26             if (wordDoc2 != null)
27             {
28                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
29                 wordDoc2 = null;
30             }
31             //關閉wordApp
32             wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
33             if (wordApp != null)
34             {
35                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
36                 wordApp = null;
37             }
38         }
39         GC.Collect();
40
41

2.C#替換Word模版中的標簽內容的例子

 1// open 
 2object omissing = system.reflection.missing.value; 
 3word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass(); 
 4object readonly = false; 
 5object template = templatepath; 
 6word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly, 
 7ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, 
 8ref omissing, ref omissing, ref omissing,ref omissing,ref omissing,ref omissing,ref omissing); 
 9// modify 
10for (int i = 1; i <= doc.bookmarks.count; i++) 
11
12object j = i; 
13word.range wordrng = doc.bookmarks.get_item(ref j).range; 
14wordrng.text = "這是第" + i + "個標簽,名稱為" + doc.bookmarks.get_item(ref j).name; 
15
16
17// save 
18object savefilename = mappath(request.applicationpath + "/document") + "/" + guid.newguid().tostring() + ".doc"; 
19doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing, 
20ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing); 
21doc.close( ref omissing, ref omissing, ref omissing ); 
22wordapp.quit( ref omissing, ref omissing, ref omissing );
23
24

3.用C#實現在Word文檔中搜索文本

 1object filename="";    //要打開的文檔路徑
 2string strKey="";      //要搜索的文本
 3object MissingValue=Type.Missing;
 4
 5Word.Application wp=new Word.ApplicationClass();
 6Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
 7               ref MissingValue,ref MissingValue,
 8               ref MissingValue,ref MissingValue,
 9               ref MissingValue,ref MissingValue,
10               ref MissingValue,ref MissingValue,
11               ref MissingValue,ref MissingValue,
12               ref MissingValue,ref MissingValue,
13               ref MissingValue,ref MissingValue);
14int i=0,iCount=0;
15Word.Find wfnd;
16
17if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
18{
19     iCount=wd.Paragraphs.Count;
20    for(i=1;i<=iCount;i++)
21{
22         wfnd=wd.Paragraphs[i].Range.Find;
23         wfnd.ClearFormatting();
24         wfnd.Text=strKey;
25        if (wfnd.Execute(ref MissingValue,ref MissingValue,
26               ref MissingValue,ref MissingValue,
27               ref MissingValue,ref MissingValue,
28               ref MissingValue,ref MissingValue,
29               ref MissingValue,ref MissingValue,
30               ref MissingValue,ref MissingValue,
31               ref MissingValue,ref MissingValue,
32               ref MissingValue))
33        {
34                MessageBox.Show("文檔中包含指定的關鍵字!","搜索結果",MessageBoxButtons.OK);
35               break;
36         }
37     }
38}
39
40
41

4.C#動態生成Word文檔並填充數據

  1using System;
  2using System.Collections.Generic;
  3using System.Text;
  4using System.IO;
  5using Word;
  6
  7namespace CreateWordFile
  8{
  9    class Program
 10    {
 11        static void Main(string[] args)
 12        {
 13            CreateWordFile("");
 14        }
 15
 16        //下面的例子中包括C#對Word文檔的創建、插入表格、設置樣式等操作:
 17
 18        //(例子中代碼有些涉及數據信息部分被省略,重要是介紹一些C#操作word文檔的方法)
 19
 20        public static string CreateWordFile(string CheckedInfo)
 21        {
 22            string message = "";
 23            try
 24            {
 25                Object Nothing = System.Reflection.Missing.Value;
 26                Directory.CreateDirectory("C:/CNSI"); //創建文件所在目錄
 27                string name = "CNSI_" + "53asdf" + ".doc";
 28                object filename = "C://CNSI//" + name; //文件保存路徑
 29                //創建Word文檔
 30                Word.Application WordApp = new Word.ApplicationClass();
 31                Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
 32
 33                //添加頁眉
 34                WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
 35                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
 36                WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[頁眉內容]");
 37                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//設置右對齊
 38                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁眉設置
 39
 40                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設置文檔的行間距
 41
 42                //移動焦點並換行
 43                object count = 14;
 44                object WdLine = Word.WdUnits.wdLine;//換一行;
 45                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動焦點
 46                WordApp.Selection.TypeParagraph();//插入段落
 47
 48                //文檔中創建表格
 49                Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
 50                //設置表格樣式
 51                newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
 52                newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
 53                newTable.Columns[1].Width = 100f;
 54                newTable.Columns[2].Width = 220f;
 55                newTable.Columns[3].Width = 105f;
 56
 57                //填充表格內容
 58                newTable.Cell(1, 1).Range.Text = "產品詳細信息表";
 59                newTable.Cell(1, 1).Range.Bold = 2;//設置單元格中字體為粗體
 60                //合並單元格
 61                newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
 62                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
 63                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
 64
 65                //填充表格內容
 66                newTable.Cell(2, 1).Range.Text = "產品基本信息";
 67                newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//設置單元格內字體顏色
 68                //合並單元格
 69                newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
 70                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
 71
 72                //填充表格內容
 73                newTable.Cell(3, 1).Range.Text = "品牌名稱:";
 74                newTable.Cell(3, 2).Range.Text = "BrandName";
 75                //縱向合並單元格
 76                newTable.Cell(3, 3).Select();//選中一行
 77                object moveUnit = Word.WdUnits.wdLine;
 78                object moveCount = 5;
 79                object moveExtend = Word.WdMovementType.wdExtend;
 80                WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
 81                WordApp.Selection.Cells.Merge();
 82                //插入圖片
 83                string FileName = "c:\\Winter.jpg";//圖片所在路徑
 84                object LinkToFile = false;
 85                object SaveWithDocument = true;
 86                object Anchor = WordDoc.Application.Selection.Range;
 87                WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
 88                WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//圖片寬度
 89                WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//圖片高度
 90                //將圖片設置為四周環繞型
 91                Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
 92                s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
 93
 94                newTable.Cell(12, 1).Range.Text = "產品特殊屬性";
 95                newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
 96                //在表格中增加行
 97                WordDoc.Content.Tables[1].Rows.Add(ref Nothing);
 98
 99                WordDoc.Paragraphs.Last.Range.Text = "文檔創建時間:" + DateTime.Now.ToString();//“落款”
100                WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
101
102                //文件保存
103                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);
104                WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
105                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
106                message = name + "文檔生成成功,以保存到C:CNSI下";
107            }
108            catch
109            {
110                message = "文件導出異常!";
111                
112            }
113            Console.WriteLine(message);
114            return message;
115        }
116
117

5.C# 將Word,Excel轉換成Html

 1//Word -〉Html
 2
 3Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//實例化一個Word
 4Type wordtype = appclass.GetType();
 5Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//獲取Document
 6Type docstype = docs.GetType();
 7object filename = ;//n.FullPath為Word文件的路徑
 8Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docstype.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,new object[]{filename,true,true});//打開文件
 9Type doctype = doc.GetType();
10object savefilename = Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath.Split('.').GetValue(0)+".html";
11doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存為Html格式
12wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出
13Thread.Sleep(3000);//為了使退出完全,這里阻塞3秒
14StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312"));   //以下內容是為了在Html中加入對本身Word文件的下載       
15FileStream fs = new FileStream(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",FileMode.Create);
16streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
17streamHtmlHelp.WriteLine("<a href=\""+n.Text+"\">源文件下載</a><br>");
18do 
19{
20     str = objreader.ReadLine();
21     streamHtmlHelp.WriteLine(str);
22}
23while (str != "</html>");
24streamHtmlHelp.Close();
25objreader.Close();
26File.Delete(savefilename.ToString());
27File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",savefilename.ToString());Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath
28
29//Excel -〉Html(這個與Word不同,因為Excel為很多層,又並列很多層,必須都清空才能銷毀實例,但實際中我發現並不是每次都能銷毀,所以網上求解多次沒有結果,只能殺沒進程,為了保證只殺滅最近的進程,我用時間進行判斷)
30
31Microsoft.Office.Interop.Excel.Application   repExcel   =   new   Microsoft.Office.Interop.Excel.Application ();//實例化Excel
32Microsoft.Office.Interop.Excel.Workbook   workbook   =   null;         
33Microsoft.Office.Interop.Excel.Worksheet worksheet   =   null;
34workbook   =   repExcel.Application.Workbooks.Open();//打開文件,n.FullPath是文件路徑
35worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
36object   htmlFile   =   Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath.Split('.').GetValue(0)+".html";   
37object   ofmt   =   Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;   
38workbook.SaveAs(htmlFile,ofmt,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);//進行另存為操作   
39object   osave   =   false;         
40workbook.Close(osave,Type.Missing,Type.Missing);//逐步關閉所有使用的對象
41repExcel.Quit();
42System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
43worksheet = null;
44GC.Collect();//垃圾回收
45System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
46workbook=null;
47GC.Collect();
48System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
49GC.Collect();
50System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
51repExcel = null;
52GC.Collect();
53System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");//依據時間殺滅進程
54foreach ( System.Diagnostics.Process p in process)
55{
56     if (DateTime.Now.Second - p.StartTime.Second > 0 && DateTime.Now.Second - p.StartTime.Second < 5)
57     {
58           p.Kill();
59      }
60}
61Thread.Sleep(3000);//保證完全關閉
62StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下內容是在Html的第一個框架中添加下載原Excel的超鏈接         
63FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001$.html",FileMode.Create);
64streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
65streamHtmlHelp.WriteLine("<a href=\""+"../"+n.Text+"\">源文件下載</a><br>");
66do 
67{
68     str = objreader.ReadLine();
69     streamHtmlHelp.WriteLine(str);
70}
71while (str != "</html>");
72streamHtmlHelp.Close();
73objreader.Close();
74File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html");
75File.Move(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001$.html",htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html");Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing
76

6.c# 實現Word聯接Excel的MailMerge功能

  1//目標:使用word的MailMerge功能,數據源是Excel中的數據。這些資料在網上很少,只能自己慢慢測試了。
  2
  3//關於Word的MailMerge功能:
  4
  5//word提供郵件的模板,可以選擇各種數據源,比如數據庫,excel等,然后群發(或打印、另存文件)郵件。
  6
  7 
  8
  9//為了實現這個功能,我的程序要能做的是
 10
 11//1:打開word文件對象
 12
 13//2:設置MailMerge數據源:指定Excel,指定查詢語句,指定聯接的列s
 14
 15//3:關閉保存
 16
 17 
 18
 19//關於引用:
 20
 21using Word = Microsoft.Office.Interop.Word;
 22
 23using System.Reflection;
 24
 25using System.Diagnostics;
 26
 27using System.IO;
 28
 29//關於變量:word的com對象需要傳入的參數定義
 30
 31Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
 32
 33object missing = System.Reflection.Missing.Value; 
 34
 35object falseValue = false;
 36
 37object trueValue = true;
 38
 39//關於處理
 40
 41//需要注重的是
 42
 43//1:打開word的方式
 44
 45//2:query的寫法。類似於sql一般,比較好玩。
 46
 47//3:設置列,。設置之后,在word中可以看見這些列。
 48
 49//4:關閉word之后,還得再copy一次excel。直接生成之后的excel文件size暴漲,文件還打不開,所以覆蓋一遍了之。原因不詳。
 50
 51private void button1_Click(object sender, EventArgs e)
 52
 53{
 54
 55object fileName = CopyTemplateDoc();//copy doc in
 56
 57Word.Document doc = WordApp.Documents.Open(ref fileName, ref missing, ref falseValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref trueValue, ref missing, ref missing, ref missing);
 58
 59object linkTo = CopyExcelData();//copy excel data
 60
 61object query = "SELECT * FROM `Sheet1$`";//data from sheet1
 62
 63object header = "Name,Category,Address,Content";//filed list
 64
 65try
 66
 67{
 68
 69doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
 70
 71doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
 72
 73MessageBox.Show("success");
 74
 75}
 76
 77catch (Exception ex)
 78
 79{
 80
 81MessageBox.Show(ex.Message);
 82
 83}
 84
 85finally
 86
 87{
 88
 89doc.Save();//save word
 90
 91CloseApp();//close word app
 92
 93CopyExcelData();//copy data again,*******************
 94
 95}
 96
 97}
 98
 99//關於關閉word對象
100
101public void CloseApp()
102{
103WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
104WordApp.Quit(ref trueValue, ref missing, ref missing);
105System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
106GC.Collect();
107
108//this.KillExcelProcess();
109}
110
111//還有兩個工具函數不再贅述,用來copy文件並且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
112

7.c#操作word表格

  1//對word中表格的操作,以下是部分代碼,關於操作不規則表格的.
  2using System;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Data;
  6using System.Drawing;
  7using System.Web;
  8using System.Web.SessionState;
  9using System.Web.UI;
 10using System.Web.UI.WebControls;
 11using System.Web.UI.HtmlControls;
 12using System.Configuration;
 13using System.IO; 
 14
 15using System.Reflection;
 16using System.Runtime.InteropServices ;
 17using System.Threading;
 18
 19public void MakeMyTable(DataTable DT,string strFilePath)
 20   {
 21   
 22    string strEnd   = this.txtEnd.Text.Trim().ToString();
 23    string strStart = this.txtStart.Text.Trim().ToString();
 24//生成文檔分頁中的起始和終止頁
 25    string strSign = "("+strStart + "-" + strEnd + ")";
 26
 27    //殺掉所有word進程以保證速度
 28    //KillWordProcess();
 29
 30    object Nothing = System.Reflection.Missing.Value; 
 31    object missing = System.Reflection.Missing.Value; 
 32    object filename= strFilePath;
 33
 34    Word.Application wordApp=new Word.ApplicationClass(); 
 35    Word.Document wordDoc=wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
 36
 37    try
 38    {
 39     //生成過程中屏蔽返回按扭,不允許中途停止
 40     Button2.Enabled = false;
 41     生成文檔
527
528   
529
530    }
531    catch
532    {
533     wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); 
534     wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); 
535     if ( wordDoc != null )
536     {
537      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
538      wordDoc = null;
539     }
540     if ( wordApp != null )
541     {
542      System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
543      wordApp = null;
544     }
545     GC.Collect();
546     utility.ShowPopMessage("文檔生成失敗!");
547
548    }
549   }
550
551

8.c#讀取Word

  1//1:
  2//對項目添加引用,Microsoft Word 11.0 Object //Library
  3//2:
  4//在程序中添加 using Word = Microsoft.Office.Interop.Word; 
  5//3:
  6//程序中添加
  7Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打開word程序
  8Word.Document doc = null; //一會要記錄word打開的文檔
  9//word文檔和word程序可不是一回事奧!
 104:
 11//一般來說,對於抽取word內容,用的方法很少
 12public override void openFile(object fileName){} //打開文檔
 13public override object readPar(int i){} //讀取word文檔的第i段
 14public override int getParCount(){} //返回word文檔一共幾段
 15public override void closeFile(){} //關閉文檔
 16public override void quit(){} //關閉word程序
 17
 18//從網頁上拷貝的目錄有時候會出現手動換行符^l,,先將其換成回車段落標記,才能正確讀取
 19public void replaceChar(){}
 20
 215:代碼
 22
 23public override void openFile(object fileName)
 24        {
 25            try
 26            {
 27                if (app.Documents.Count > 0)
 28                {
 29                    if (MessageBox.Show("已經打開了一個word文檔,你想關閉重新打開該文檔嗎?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
 30                    {
 31                        object unknow = Type.Missing;
 32                        doc = app.ActiveDocument;
 33                        if (MessageBox.Show("你想保存嗎?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
 34                        {
 35                            app.ActiveDocument.Save();
 36                        }
 37
 38                        app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
 39                        app.Visible = false;
 40                    }
 41                    else
 42                    {
 43                        return;
 44                    }
 45                }
 46            }
 47            catch (Exception)
 48            {
 49                //MessageBox.Show("您可能關閉了文檔");
 50                app = new Microsoft.Office.Interop.Word.Application();
 51            }
 52
 53            try
 54            {
 55                object unknow = Type.Missing;
 56                app.Visible = true;
 57                doc = app.Documents.Open(ref fileName,
 58                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
 59                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
 60                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
 61             }
 62             catch (Exception ex)
 63             {
 64                 MessageBox.Show("出現錯誤:" + ex.ToString());
 65             }   
 66           
 67        }
 68public override object readPar(int i)
 69        {
 70            try
 71            {
 72                string temp = doc.Paragraphs[i].Range.Text.Trim();
 73                return temp;
 74            }
 75            catch (Exception e) {
 76                MessageBox.Show("Error:"+e.ToString());
 77                return null;
 78            }
 79        }
 80
 81public override int getParCount()
 82        {
 83            return doc.Paragraphs.Count;
 84        }
 85
 86public override void closeFile()
 87        {
 88            try
 89            {
 90                object unknow = Type.Missing;
 91                object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
 92                app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
 93            }
 94            catch (Exception ex)
 95            {
 96                MessageBox.Show("Error:" + ex.ToString());
 97            }
 98        }
 99
100public override void quit()
101        {
102            try
103            {
104                object unknow = Type.Missing;
105                object saveChanges = Word.WdSaveOptions.wdSaveChanges;
106                app.Quit(ref saveChanges, ref unknow, ref unknow);
107            }
108            catch (Exception)
109            {
110
111            }
112        }
113
114public void replaceChar() {
115            try
116            {
117                object replaceAll = Word.WdReplace.wdReplaceAll;
118                object missing = Type.Missing;
119
120                app.Selection.Find.ClearFormatting();
121                app.Selection.Find.Text = "^l";
122
123                app.Selection.Find.Replacement.ClearFormatting();
124                app.Selection.Find.Replacement.Text = "^p";
125
126                app.Selection.Find.Execute(
127                    ref missing, ref missing, ref missing, ref missing, ref missing,
128                    ref missing, ref missing, ref missing, ref missing, ref missing,
129                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);
130            }
131            catch (Exception e)
132            {
133                MessageBox.Show("文檔出現錯誤,請重新操作");
134            }
135        }
136
137//6:
138//剛才是用讀取一段做的例子,如果要讀取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因為都是微軟的東東,所以用起來沒有一點的障礙,再加上現在的vs2005做的很智能,所以先從java轉到了c#上
139
140//7:
141//實際上,c#中讀取word是不用那么麻煩的,但是如果考慮到可能還要抽取txt,ppt等多種格式,所以就寫了一個抽象類,調用起來也方便,這就是為什么我的程序方法開頭會有override的原因,總要考慮到通用,所以多了一些代碼。
142
143

9.C#打開WORD文檔內容並顯示

 1private void button1_Click(object sender, System.EventArgs e)
 2   {
 3    //調用打開文件對話框獲取要打開的文件WORD文件,RTF文件,文本文件路徑名稱
 4    OpenFileDialog opd = new OpenFileDialog();
 5    opd.InitialDirectory = "c:\\";
 6    opd.Filter = "Word文檔(*.doc)|*.doc|文本文檔(*.txt)|*.txt|RTF文檔(*.rtf)|*.rtf|所有文檔(*.*)|*.*";
 7    opd.FilterIndex = 1;
 8   
 9    if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
10    {   
11   
12     //建立Word類的實例,缺點:不能正確讀取表格,圖片等等的顯示
13     Word.ApplicationClass app = new Word.ApplicationClass();
14     Word.Document doc = null;
15     object missing = System.Reflection.Missing.Value;
16
17     object FileName = opd.FileName;
18     object readOnly = false;
19     object isVisible = true;
20     object index = 0;
21     try
22     {
23      doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
24       ref missing, ref missing, ref missing, ref missing, ref missing,
25       ref missing, ref missing, ref missing, ref isVisible, ref missing,
26       ref missing, ref missing, ref missing);
27
28      doc.ActiveWindow.Selection.WholeStory();
29      doc.ActiveWindow.Selection.Copy(); 
30      //從剪切板獲取數據
31      IDataObject data=Clipboard.GetDataObject();
32      this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
33      
34     }
35     finally
36     {
37      if (doc != null)
38      {
39       doc.Close(ref missing, ref missing, ref missing);
40       doc = null;
41      }
42
43      if (app != null)
44      {
45       app.Quit(ref missing, ref missing, ref missing);
46       app = null;
47      }
48     }
49
50    }
51
52   }


免責聲明!

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



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