C#操作word文档

来源:互联网 发布:愚公移山h5 运营数据 编辑:程序博客网 时间:2024/05/03 11:51

 

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模版中的标签内容的例子
Code

3.用C#实现在Word文档中搜索文本
Code

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, 123ref 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(11).Range.Text = "产品详细信息表";
 59                newTable.Cell(11).Range.Bold = 2;//设置单元格中字体为粗体
 60                //合并单元格
 61                newTable.Cell(11).Merge(newTable.Cell(13));
 62                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
 63                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
 64
 65                //填充表格内容
 66                newTable.Cell(21).Range.Text = "产品基本信息";
 67                newTable.Cell(21).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
 68                //合并单元格
 69                newTable.Cell(21).Merge(newTable.Cell(23));
 70                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
 71
 72                //填充表格内容
 73                newTable.Cell(31).Range.Text = "品牌名称:";
 74                newTable.Cell(32).Range.Text = "BrandName";
 75                //纵向合并单元格
 76                newTable.Cell(33).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(121).Range.Text = "产品特殊属性";
 95                newTable.Cell(121).Merge(newTable.Cell(123));
 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
Code

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

7.c#操作word表格
Code

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文档内容并显示
Code
原创粉丝点击