天天看點

C#操作word文檔(一)

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

using Word = Microsoft.Office.Interop.Word;

object Nothing = System.Reflection.Missing.Value;

         object format = Word.WdSaveFormat.wdFormatDocument;

         Word.Application wordApp = new Word.ApplicationClass();

         //打開網頁選擇内容

         object srcFileName = @"c:\new1.doc"; //裡面有圖檔

          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

         {

             //關閉網頁wordDoc2

             wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);

             if (wordDoc2 != null)

             {

                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);

                 wordDoc2 = null;

             }

             //關閉wordApp

             wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

             if (wordApp != null)

             {

                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);

                 wordApp = null;

             }

         }

         GC.Collect();

2.C#替換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 = "這是第" + i + "個标簽,名稱為" + 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.用C#實作在Word文檔中搜尋文本

object filename="

C#操作word文檔(一)
";    //要打開的文檔路徑
C#操作word文檔(一)
string strKey="
C#操作word文檔(一)
";      //要搜尋的文本
C#操作word文檔(一)
object MissingValue=Type.Missing;
C#操作word文檔(一)
C#操作word文檔(一)
Word.Application wp=new Word.ApplicationClass();
C#操作word文檔(一)
Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)

               ref MissingValue,ref MissingValue);

int i=0,iCount=0;

C#操作word文檔(一)
Word.Find wfnd;
C#操作word文檔(一)
C#操作word文檔(一)
if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
C#操作word文檔(一)
{
C#操作word文檔(一)
     iCount=wd.Paragraphs.Count;
C#操作word文檔(一)
    for(i=1;i<=iCount;i++)
C#操作word文檔(一)
{
C#操作word文檔(一)
         wfnd=wd.Paragraphs[i].Range.Find;
C#操作word文檔(一)
         wfnd.ClearFormatting();
C#操作word文檔(一)
         wfnd.Text=strKey;
C#操作word文檔(一)
        if (wfnd.Execute(ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue,ref MissingValue,
C#操作word文檔(一)
               ref MissingValue))
C#操作word文檔(一)
        {
C#操作word文檔(一)
                MessageBox.Show("文檔中包含指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
C#操作word文檔(一)
               break;
C#操作word文檔(一)
         }
C#操作word文檔(一)
     }
C#操作word文檔(一)

}

4.C#.net操作Word文檔:以Office 2007為例

首先引入類庫,Microsoft.Office.Interop.Word,然後進行程式設計。代碼如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.Office.Interop.Word;

namespace WordTest

{

public partial class Form1 : Form

{

object strFileName;

Object Nothing;

Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

Document myWordDoc;

string strContent = "";

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

createWord();

//openWord();

}

private void createWord()

{

strFileName = System.Windows.Forms.Application.StartupPath + "test.doc";

if (System.IO.File.Exists((string)strFileName))

System.IO.File.Delete((string)strFileName);

Object Nothing = System.Reflection.Missing.Value;

myWordDoc = myWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

#region 将資料庫中讀取得資料寫入到word檔案中

strContent = "你好\n\n\r";

myWordDoc.Paragraphs.Last.Range.Text = strContent;

strContent = "這是測試程式";

myWordDoc.Paragraphs.Last.Range.Text = strContent;

#endregion

//将WordDoc文檔對象的内容儲存為DOC文檔

myWordDoc.SaveAs(ref strFileName, 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文檔對象

myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

//關閉WordApp元件對象

myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

this.richTextBox1.Text = strFileName + "\r\n" + "建立成功";

}

private void openWord()

{

fontDialog1.ShowDialog();

System.Drawing.Font font = fontDialog1.Font;

object filepath = "D:\\asp.docx";

object oMissing = System.Reflection.Missing.Value;

myWordDoc = myWordApp.Documents.Open(ref filepath, 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);

myWordDoc.Content.Font.Size = font.Size;

myWordDoc.Content.Font.Name = font.Name;

myWordDoc.Save();

richTextBox1.Text = myWordDoc.Content.Text;

myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);

myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);

}

}

5.C#動态生成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("");

        }

        //下面的例子中包括C#對Word文檔的建立、插入表格、設定樣式等操作:

        //(例子中代碼有些涉及資料資訊部分被省略,重要是介紹一些C#操作word文檔的方法)

        public static string CreateWordFile(string CheckedInfo)

        {

            string message = "";

            try

            {

                Object Nothing = System.Reflection.Missing.Value;

                Directory.CreateDirectory("C:/CNSI"); //建立檔案所在目錄

                string name = "CNSI_" + "53asdf" + ".doc";

                object filename = "C://CNSI//" + name; //檔案儲存路徑

                //建立Word文檔

                Word.Application WordApp = new Word.ApplicationClass();

                Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                //添加頁眉

                WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;

                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

                WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[頁眉内容]");

                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//設定右對齊

                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁眉設定

                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設定文檔的行間距

                //移動焦點并換行

                object count = 14;

                object WdLine = Word.WdUnits.wdLine;//換一行;

                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動焦點

                WordApp.Selection.TypeParagraph();//插入段落

                //文檔中建立表格

                Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);

                //設定表格樣式

                newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;

                newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;

                newTable.Columns[1].Width = 100f;

                newTable.Columns[2].Width = 220f;

                newTable.Columns[3].Width = 105f;

                //填充表格内容

                newTable.Cell(1, 1).Range.Text = "産品詳細資訊表";

                newTable.Cell(1, 1).Range.Bold = 2;//設定單元格中字型為粗體

                //合并單元格

                newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));

                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水準居中

                //填充表格内容

                newTable.Cell(2, 1).Range.Text = "産品基本資訊";

                newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//設定單元格内字型顔色

                //合并單元格

                newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));

                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //填充表格内容

                newTable.Cell(3, 1).Range.Text = "品牌名稱:";

                newTable.Cell(3, 2).Range.Text = "BrandName";

                //縱向合并單元格

                newTable.Cell(3, 3).Select();//選中一行

                object moveUnit = Word.WdUnits.wdLine;

                object moveCount = 5;

                object moveExtend = Word.WdMovementType.wdExtend;

                WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);

                WordApp.Selection.Cells.Merge();

                //插入圖檔

                string FileName = "c:\\Winter.jpg";//圖檔所在路徑

                object LinkToFile = false;

                object SaveWithDocument = true;

                object Anchor = WordDoc.Application.Selection.Range;

                WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

                WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//圖檔寬度

                WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//圖檔高度

                //将圖檔設定為四周環繞型

                Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();

                s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

                newTable.Cell(12, 1).Range.Text = "産品特殊屬性";

                newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));

                //在表格中增加行

                WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

                WordDoc.Paragraphs.Last.Range.Text = "文檔建立時間:" + DateTime.Now.ToString();//“落款”

                WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                //檔案儲存

                WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

                message = name + "文檔生成成功,以儲存到C:CNSI下";

            }

            catch

            {

                message = "檔案導出異常!";

            }

            Console.WriteLine(message);

            return message;

        }