C#操作word文档(转)

来源:互联网 发布:琅琊榜香港遇冷 知乎 编辑:程序博客网 时间:2024/04/30 08:22

http://hzhg12345.blog.163.com/blog/static/45376342200851771820444/

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="";    //要打开的文档路径

string strKey="";      //要搜索的文本

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("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);

               break;

         }

     }

}

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;

        }

6.C# 将Word,Excel转换成Html

Word -〉Html

Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//实例化一个Word

Type wordtype = appclass.GetType();

Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//获取Document

Type docstype = docs.GetType();

object filename = ;//n.FullPath为Word文件的路径

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});//打开文件

Type doctype = doc.GetType();

object savefilename = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";

doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存为Html格式

wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出

Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒

StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312"));   //以下内容是为了在Html中加入对本身Word文件的下载       

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=/""+n.Text+"/">源文件下载</a><br>");

do

{

     str = objreader.ReadLine();

     streamHtmlHelp.WriteLine(str);

}

while (str != "</html>");

streamHtmlHelp.Close();

objreader.Close();

File.Delete(savefilename.ToString());

File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",savefilename.ToString()););//打开文件,n.FullPath是文件路径

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);//进行另存为操作   

object   osave   =   false;         

workbook.Close(osave,Type.Missing,Type.Missing);//逐步关闭所有使用的对象

repExcel.Quit();

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

worksheet = null;

GC.Collect();//垃圾回收

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");//依据时间杀灭进程

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);//保证完全关闭

StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下内容是在Html的第一个框架中添加下载原Excel的超链接         

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=/""+"../"+n.Text+"/">源文件下载</a><br>");

do

{

     str = objreader.ReadLine();

     streamHtmlHelp.WriteLine(str);

}

while (str != "</html>");

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

的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。

关于Word的MailMerge功能:

word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。

 

7.c# 实现Word联接Excel的MailMerge功能

目标:使用word

为了实现这个功能,我的程序要能做的是

1:打开word文件对象

2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s

3:关闭保存

 

关于引用:

using Word = Microsoft.Office.Interop.Word;

using System.Reflection;

using System.Diagnostics;

using System.IO;

关于变量:word的com对象需要传入的参数定义

Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();

object missing = System.Reflection.Missing.Value;

object falseValue = false;

object trueValue = true;

关于处理

需要注重的是

1:打开word的方式

2:query的写法。类似于sql一般,比较好玩。

3:设置列,。设置之后,在word中可以看见这些列。

4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。

private void button1_Click(object sender, EventArgs e)

{

object fileName = CopyTemplateDoc();//copy doc in

Word.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);

object linkTo = CopyExcelData();//copy excel data

object query = "SELECT * FROM `Sheet1$`";//data from sheet1

object header = "Name,Category,Address,Content";//filed list

try

{

doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);

doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test

MessageBox.Show("success");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

finally

{

doc.Save();//save word

CloseApp();//close word app

CopyExcelData();//copy data again,*******************

}

}

关于关闭word对象

public void CloseApp()

{

WordApp.Documents.Close(ref trueValue, ref missing, ref missing);

WordApp.Quit(ref trueValue, ref missing, ref missing);

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

GC.Collect();

//this.KillExcelProcess();

}

还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。

原创粉丝点击