Summarize C# Control Word Skills(C#操作Word技巧总结)

原文地址链接:http://www.codeproject.com/Articles/201439/Summarize-C-Control-Word-Skills

1、在特定的书签(标记)中插入文本或者图片。

 

using Word = Microsoft.Office.Interop.Word;
 
     object Nothing = System.Reflection.Missing.Value;
     object format = Word.WdSaveFormat.wdFormatDocument;
     Word.Application wordApp = new Word.ApplicationClass();
     //open website and choose content
     object srcFileName = @"c:\new1.doc"; // images inside
     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);
       try
          {
          object bookmarkName = "jlr";
          //Word.Range rng = wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range;
          //rng.Text = "newText";
          //object range = rng;
          //wordDoc2.Bookmarks.Add("jlr", ref range);
          wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();
           wordApp.Selection.InlineShapes.AddPicture
		("c:\\1.jpg", ref Nothing, ref Nothing, ref Nothing);
         wordDoc2.Save();

         }
     catch { }
     finally
     		{
         // Close website wordDoc2
         wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);
         if (wordDoc2 != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
             wordDoc2 = null;
         }
         // close wordApp
         wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
         if (wordApp != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
             wordApp = null;
         }
     		}
     GC.Collect();


2、替换Word模板中的书签内容。

// open 
object omissing = system.reflection.missing.value; 
word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass(); 
object readonly = false; 
object template = templatepath; 
word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly, 
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); 
// modify 
for (int i = 1; i <= doc.bookmarks.count; i++) 
{ 
    object j = i; 
    word.range wordrng = doc.bookmarks.get_item(ref j).range; 
    wordrng.text = "This is the" + i + "bookmark, name as" + 
			doc.bookmarks.get_item(ref j).name; 
} 

// save 
object savefilename = mappath(request.applicationpath + "/document") + 
	"/" + guid.newguid().tostring() + ".doc"; 
doc.saveas(ref savefilename,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); 
   doc.close( ref omissing, ref omissing, ref omissing );  
wordapp.quit( ref omissing, ref omissing, ref omissing );


3、在Word中搜索文本内容。

     object filename="";    // file path
     string strKey="";      // text which you want o search
     object MissingValue=Type.Missing;

     Word.Application wp=new Word.ApplicationClass();
     Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue,
             ref MissingValue,ref MissingValue);
     int i=0,iCount=0;
     Word.Find wfnd;

     if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
			{
  			iCount=wd.Paragraphs.Count;
 		for(i=1;i<=iCount;i++)
   		{
  			wfnd=wd.Paragraphs[i].Range.Find;
  			wfnd.ClearFormatting();
  			wfnd.Text=strKey;
 		if (wfnd.Execute(ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue,ref MissingValue,
        ref MissingValue))
       {
                MessageBox.Show("include designated keyword!",
			"search result",MessageBoxButtons.OK);
        break;
         }
      }
}


4、动态生成Word文件,并在其中插入数据。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Word;
  
namespace CreateWordFile
{
    class Program
       {
        static void Main(string[] args)
      {
       CreateWordFile("");
      }
 
   // The example below includes C# create Word, insert table and set up style:
 
   // Our point is to introduce some methods of C# control Word file. 
   // So some involved information was omitted.

public static string CreateWordFile(string CheckedInfo)
 {
          string message = "";
    try
   			{
       Object Nothing = System.Reflection.Missing.Value;
       Directory.CreateDirectory("C:/CNSI"); // Create file category 
       string name = "CNSI_" + "53asdf" + ".doc";
       object filename = "C://CNSI//" + name; // file save path
       // create Word file
       Word.Application WordApp = new Word.ApplicationClass();
         Word.Document WordDoc = WordApp.Documents.Add
		(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
    // Add header
    WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
    WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
    WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
    WordApp.Selection.ParagraphFormat.Alignment = 
	Word.WdParagraphAlignment.wdAlignParagraphRight;// Set right alignment 
    WordApp.ActiveWindow.View.SeekView = 
		WdSeekView.wdSeekMainDocument;// set pop up header 

    WordApp.Selection.ParagraphFormat.LineSpacing = 15f;// Set file line spacing
  
         // Move focus and newline
         object count = 14;
         object WdLine = Word.WdUnits.wdLine;//newline;
    WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//move focus
      WordApp.Selection.TypeParagraph();// insert paragraph

         // Create table in Word file
         Word.Table newTable = WordDoc.Tables.Add
		(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
         // Set table style
        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;

         // Fill in table
       newTable.Cell(1, 1).Range.Text = "Product information table";
       newTable.Cell(1, 1).Range.Bold = 2;// Set text font as bold in Cells
         // Merge cells
       newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
       WordApp.Selection.Cells.VerticalAlignment = 
	Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;// Center Vertically 
       WordApp.Selection.ParagraphFormat.Alignment = 
	Word.WdParagraphAlignment.wdAlignParagraphCenter;// Center Horizontal 

         // Fill in table
         newTable.Cell(2, 1).Range.Text = " Product information table ";
         newTable.Cell(2, 1).Range.Font.Color = 
		Word.WdColor.wdColorDarkBlue;// Set   text color in Cells
         //Merge Cells
         newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
         WordApp.Selection.Cells.VerticalAlignment = 
		Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

         // Fill in table
         newTable.Cell(3, 1).Range.Text = "Brandname";
         newTable.Cell(3, 2).Range.Text = "BrandName";
         // merge cells longitudinal 
         newTable.Cell(3, 3).Select();// choose a row
         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();
         // insert image
         string FileName = "c:\\Winter.jpg";// image path
         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;//image width
         WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//image height
         // Set image layout as Square 
         Word.Shape s = 
		WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
        s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

        newTable.Cell(12, 1).Range.Text = "product special attribute";
        newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
        // Add rows in table
        WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

   	WordDoc.Paragraphs.Last.Range.Text = "Created date:" + 
				DateTime.Now.ToString();//“Alignment”
	WordDoc.Paragraphs.Last.Alignment = 
				Word.WdParagraphAlignment.wdAlignParagraphRight;

        // Save file
        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 + " File created successful, save to C:CNSI";
    }
    catch
    {
        message = "File export error!";        
    }
    Console.WriteLine(message);
    return message;
}


5、转换Word、Excel到Html文件。

       //Word -〉Html
       Microsoft.Office.Interop.Word.ApplicationClass appclass = 
		new Microsoft.Office.Interop.Word.ApplicationClass();//Sample Word
 	Type wordtype = appclass.GetType();
 	Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;
      //Get Document
 	Type docstype = docs.GetType();
	object filename = ;//n.FullPath is Word file path
 	 Microsoft.Office.Interop.Word.Document doc = 
		(Microsoft.Office.Interop.Word.Document)docstype.InvokeMember
		("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,
		new object   {filename,true,true});// Open file
        Type doctype = doc.GetType();
        object savefilename = <a href="mailto:Application.StartupPath+@%22%5Cccyt_chm%5Cinform%5C%22+n.FullPath.Split%28%27.%27%29.GetValue%280%29+%22.html%22;doctype.InvokeMember%28%22SaveAs%22,System.Reflection.BindingFlags.InvokeMethod,null,doc,new">Application.StartupPath+@"\ccyt_chm\inform\"+
				n.FullPath.Split('.').GetValue(0)+".html";
doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,
	null,doc,new</a> object[]{savefilename,
	Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});// Save as Html format
 		wordtype.InvokeMember
		("Quit",System.Reflection.BindingFlags.InvokeMethod,
			null,appclass,null);// Exit
Thread.Sleep(3000);// choke 3 seconds for safely exiting  
 	StreamReader objreader = new StreamReader(savefilename.ToString(),
	System.Text.Encoding.GetEncoding("GB2312"));   // the content below is to 
					// add the word file download in Html     
FileStream fs = new FileStream(savefilename.ToString().Split
		('.').GetValue(0).ToString()+"$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter
	(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+n.Text+%22%5C%22">Source file download</a>");
do 
   {
        str = objreader.ReadLine();
        streamHtmlHelp.WriteLine(str);
   }
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(savefilename.ToString()); 
File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",
    savefilename.ToString());Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath

        //Excel -〉Html
 	Microsoft.Office.Interop.Excel.Application   repExcel   =   
		new   Microsoft.Office.Interop.Excel.Application ();//Sample Excel
	Microsoft.Office.Interop.Excel.Workbook   workbook   =   null;         
	Microsoft.Office.Interop.Excel.Worksheet worksheet   =   null;
	workbook   =   repExcel.Application.Workbooks.Open();//Open file,
						//n.FullPathis the file path
	worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
 	object   htmlFile   =   Application.StartupPath+@"\ccyt_chm\inform\"+
					n.FullPath.Split('.').GetValue(0)+".html";   
object   ofmt   =   Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;   
 workbook.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);//save as 
object   osave   =   false;         
workbook.Close(osave,Type.Missing,Type.Missing);// close objects one by one 
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
GC.Collect();// recycle 
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook=null;
GC.Collect();

System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
repExcel = null;
GC.Collect();
 System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName
		("EXCEL");// close process according to the time
foreach ( System.Diagnostics.Process p in process)
 {
  if (DateTime.Now.Second - p.StartTime.Second > 0 && 
		DateTime.Now.Second - p.StartTime.Second < 5)
    {
         p.Kill();
    }
 }
 Thread.Sleep(3000);// guarantee completely shut download 
 StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+
	".files\\sheet001.html",System.Text.Encoding.GetEncoding
	("GB2312"));	// The content below is to add an original excel download 
			//hyperlink in the first Excel frame.        
 FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue
			(0)+".files\\sheet001$.html",FileMode.Create);
 streamHtmlHelp = new System.IO.StreamWriter
		(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+%22../%22+n.Text+%22%5C%22">
			Source code download</a>
");
do 
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html");
 File.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


6、通过邮件合并功能连接(合并)Word或Excel文档。

       //Word -〉Html
       Microsoft.Office.Interop.Word.ApplicationClass appclass = 
		new Microsoft.Office.Interop.Word.ApplicationClass();//Sample Word
 	Type wordtype = appclass.GetType();
 	Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;
      //Get Document
 	Type docstype = docs.GetType();
	object filename = ;//n.FullPath is Word file path
 	 Microsoft.Office.Interop.Word.Document doc = 
		(Microsoft.Office.Interop.Word.Document)docstype.InvokeMember
		("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,
		new object   {filename,true,true});// Open file
        Type doctype = doc.GetType();
        object savefilename = <a href="mailto:Application.StartupPath+@%22%5Cccyt_chm%5Cinform%5C%22+n.FullPath.Split%28%27.%27%29.GetValue%280%29+%22.html%22;doctype.InvokeMember%28%22SaveAs%22,System.Reflection.BindingFlags.InvokeMethod,null,doc,new">Application.StartupPath+@"\ccyt_chm\inform\"+
				n.FullPath.Split('.').GetValue(0)+".html";
doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,
	null,doc,new</a> object[]{savefilename,
	Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});// Save as Html format
 		wordtype.InvokeMember
		("Quit",System.Reflection.BindingFlags.InvokeMethod,
			null,appclass,null);// Exit
Thread.Sleep(3000);// choke 3 seconds for safely exiting  
 	StreamReader objreader = new StreamReader(savefilename.ToString(),
	System.Text.Encoding.GetEncoding("GB2312"));   // the content below is to 
					// add the word file download in Html     
FileStream fs = new FileStream(savefilename.ToString().Split
		('.').GetValue(0).ToString()+"$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter
	(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+n.Text+%22%5C%22">Source file download</a>");
do 
   {
        str = objreader.ReadLine();
        streamHtmlHelp.WriteLine(str);
   }
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(savefilename.ToString()); 
File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",
    savefilename.ToString());Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath

        //Excel -〉Html
 	Microsoft.Office.Interop.Excel.Application   repExcel   =   
		new   Microsoft.Office.Interop.Excel.Application ();//Sample Excel
	Microsoft.Office.Interop.Excel.Workbook   workbook   =   null;         
	Microsoft.Office.Interop.Excel.Worksheet worksheet   =   null;
	workbook   =   repExcel.Application.Workbooks.Open();//Open file,
						//n.FullPathis the file path
	worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
 	object   htmlFile   =   Application.StartupPath+@"\ccyt_chm\inform\"+
					n.FullPath.Split('.').GetValue(0)+".html";   
object   ofmt   =   Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;   
 workbook.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);//save as 
object   osave   =   false;         
workbook.Close(osave,Type.Missing,Type.Missing);// close objects one by one 
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
GC.Collect();// recycle 
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook=null;
GC.Collect();

System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
repExcel = null;
GC.Collect();
 System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName
		("EXCEL");// close process according to the time
foreach ( System.Diagnostics.Process p in process)
 {
  if (DateTime.Now.Second - p.StartTime.Second > 0 && 
		DateTime.Now.Second - p.StartTime.Second < 5)
    {
         p.Kill();
    }
 }
 Thread.Sleep(3000);// guarantee completely shut download 
 StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+
	".files\\sheet001.html",System.Text.Encoding.GetEncoding
	("GB2312"));	// The content below is to add an original excel download 
			//hyperlink in the first Excel frame.        
 FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue
			(0)+".files\\sheet001$.html",FileMode.Create);
 streamHtmlHelp = new System.IO.StreamWriter
		(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href="%5C%22%22+%22../%22+n.Text+%22%5C%22">
			Source code download</a>
");
do 
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files\\sheet001.html");
 File.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


7、读取Word文档。

//1:
// Refer to,Microsoft Word 11.0 Object //Library
//2:
//Add using Word = Microsoft.Office.Interop.Word; 
//3:
//Add in program
Word.Application app = 
	new Microsoft.Office.Interop.Word.Application(); // permit open Word process
Word.Document doc = null; // Record file opened by Word
// Word file is not Word process 
//4:
// usually, there are only a few methods to extract word content 
 public override void openFile(object fileName){} //Open file
 public override object readPar(int i){} // Read Word file, paragraph i
 public override int getParCount(){} // Back to Word file paragraph
 public override void closeFile(){} // Close file
 public override void quit(){} //Close Word process
 
 public void replaceChar(){}
 
//5: Code 
 public override void openFile(object fileName)
    {
        try
        {
            if (app.Documents.Count > 0)
            {
                if (MessageBox.Show("Already open a Word file,
		Do you want to close and reopen the file?", "reminder", 
		MessageBoxButtons.YesNo) == DialogResult.Yes)
         {
             object unknow = Type.Missing;
             doc = app.ActiveDocument;
                         if (MessageBox.Show("Do you want to save?", 
			"Save", MessageBoxButtons.YesNo) == DialogResult.Yes)
                 {
                     app.ActiveDocument.Save();
                 }

                 app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
                 app.Visible = false;
             }
             else
             {
                 return;
             }
         }
     }
     catch (Exception)
     {
         //MessageBox.Show("You might close file");
         app = new Microsoft.Office.Interop.Word.Application();
     }

     try
     {
         object unknow = Type.Missing;
         app.Visible = true;
         doc = app.Documents.Open(ref fileName,
                                  	ref unknow, ref unknow, ref unknow, 
			       	ref unknow, ref unknow,
                                  	ref unknow, ref unknow, ref unknow, 
			       	ref unknow, ref unknow,
                                  	ref unknow, ref unknow, ref unknow, 
				ref unknow, ref unknow);
      }
      catch (Exception ex)
      {
          MessageBox.Show("Error:" + ex.ToString());
      }   
    
 }
 public override object readPar(int i)
      {
       try
       {
           string temp = doc.Paragraphs[i].Range.Text.Trim();
           return temp;
       }
       catch (Exception e) {
           MessageBox.Show("Error:"+e.ToString());
           return null;
       }
   }

 public override int getParCount()
     {
         return doc.Paragraphs.Count;
     }

 public override void closeFile()
    {
        try
        {
            object unknow = Type.Missing;
            object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
            app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error:" + ex.ToString());
        }
    }
 
public override void quit()
   {
       try
       {
           object unknow = Type.Missing;
           object saveChanges = Word.WdSaveOptions.wdSaveChanges;
           app.Quit(ref saveChanges, ref unknow, ref unknow);
       }
       catch (Exception)
       {

       }
   }

public void replaceChar() {
   try
   {
       object replaceAll = Word.WdReplace.wdReplaceAll;
       object missing = Type.Missing;

       app.Selection.Find.ClearFormatting();
       app.Selection.Find.Text = "^l";

       app.Selection.Find.Replacement.ClearFormatting();
       app.Selection.Find.Replacement.Text = "^p";

       app.Selection.Find.Execute(
           ref missing, ref missing, ref missing, ref missing, ref missing,
           ref missing, ref missing, ref missing, ref missing, ref missing,
           ref replaceAll, ref missing, ref missing, ref missing, ref missing);
   }
   catch (Exception e)
   {
       MessageBox.Show("Error, please do it again");
   }
}


8、打开并显示Word文档内容。

private void button1_Click(object sender, System.EventArgs e)
      {
      //Invoke and open file dialog to get Word, RTF, text file path name
     OpenFileDialog opd = new OpenFileDialog();
     opd.InitialDirectory = "c:\\";
     opd.Filter = "Word文档(*.doc)|*.doc|Text(*.txt)|*.txt|RTF File(*.rtf)|
		*.rtf|All files(*.*)|*.*";
     opd.FilterIndex = 1;

     if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
      {   
 
       // Create Word class sample
       Word.ApplicationClass app = new Word.ApplicationClass();
       Word.Document doc = null;
       object missing = System.Reflection.Missing.Value;

       object FileName = opd.FileName;
       object readOnly = false;
       object isVisible = true;
       object index = 0;
    try
      {
       doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref isVisible, ref missing,
        ref missing, ref missing, ref missing);

       doc.ActiveWindow.Selection.WholeStory();
       doc.ActiveWindow.Selection.Copy(); 
       // Get data from clipboard
       IDataObject data=Clipboard.GetDataObject();
       this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
      }
   finally
   {
    if (doc != null)
    {
     doc.Close(ref missing, ref missing, ref missing);
     doc = null;
    }

    if (app != null)
     {
      app.Quit(ref missing, ref missing, ref missing);
      app = null;
     }
   }
 }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值