码迷,mamicode.com
首页 > 其他好文 > 详细

C# Word

时间:2014-08-12 18:07:24      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   使用   os   io   

C# 操作word文档

1.c#操作word 在指定书签插入文字或者图片

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

2.C#替换Word模版中的标签内容的例子
bubuko.com,布布扣
 1bubuko.com,布布扣// open 
 2bubuko.com,布布扣object omissing = system.reflection.missing.value; 
 3bubuko.com,布布扣word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass(); 
 4bubuko.com,布布扣object readonly = false; 
 5bubuko.com,布布扣object template = templatepath; 
 6bubuko.com,布布扣word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly, 
 7bubuko.com,布布扣ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, 
 8bubuko.com,布布扣ref omissing, ref omissing, ref omissing,ref omissing,ref omissing,ref omissing,ref omissing); 
 9bubuko.com,布布扣// modify 
10bubuko.com,布布扣for (int i = 1; i <= doc.bookmarks.count; i++) 
11bubuko.com,布布扣
12bubuko.com,布布扣object j = i; 
13bubuko.com,布布扣word.range wordrng = doc.bookmarks.get_item(ref j).range; 
14bubuko.com,布布扣wordrng.text = "这是第" + i + "个标签,名称为" + doc.bookmarks.get_item(ref j).name; 
15bubuko.com,布布扣
16bubuko.com,布布扣
17bubuko.com,布布扣// save 
18bubuko.com,布布扣object savefilename = mappath(request.applicationpath + "/document") + "/" + guid.newguid().tostring() + ".doc"; 
19bubuko.com,布布扣doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing, 
20bubuko.com,布布扣ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing); 
21bubuko.com,布布扣doc.close( ref omissing, ref omissing, ref omissing ); 
22bubuko.com,布布扣wordapp.quit( ref omissing, ref omissing, ref omissing );
23bubuko.com,布布扣
24bubuko.com,布布扣

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

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

5.C# 将Word,Excel转换成Html
bubuko.com,布布扣
 1bubuko.com,布布扣//Word -〉Html
 2bubuko.com,布布扣
 3bubuko.com,布布扣Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//实例化一个Word
 4bubuko.com,布布扣Type wordtype = appclass.GetType();
 5bubuko.com,布布扣Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//获取Document
 6bubuko.com,布布扣Type docstype = docs.GetType();
 7bubuko.com,布布扣object filename = ;//n.FullPath为Word文件的路径
 8bubuko.com,布布扣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});//打开文件
 9bubuko.com,布布扣Type doctype = doc.GetType();
10bubuko.com,布布扣object savefilename = Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath.Split(‘.‘).GetValue(0)+".html";
11bubuko.com,布布扣doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存为Html格式
12bubuko.com,布布扣wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出
13bubuko.com,布布扣Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒
14bubuko.com,布布扣StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312"));   //以下内容是为了在Html中加入对本身Word文件的下载       
15bubuko.com,布布扣FileStream fs = new FileStream(savefilename.ToString().Split(‘.‘).GetValue(0).ToString()+"$.html",FileMode.Create);
16bubuko.com,布布扣streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
17bubuko.com,布布扣streamHtmlHelp.WriteLine("<a href=\""+n.Text+"\">源文件下载</a><br>");
18bubuko.com,布布扣do 
19bubuko.com,布布扣{
20bubuko.com,布布扣     str = objreader.ReadLine();
21bubuko.com,布布扣     streamHtmlHelp.WriteLine(str);
22bubuko.com,布布扣}
23bubuko.com,布布扣while (str != "</html>");
24bubuko.com,布布扣streamHtmlHelp.Close();
25bubuko.com,布布扣objreader.Close();
26bubuko.com,布布扣File.Delete(savefilename.ToString());
27bubuko.com,布布扣File.Move(savefilename.ToString().Split(‘.‘).GetValue(0).ToString()+"$.html",savefilename.ToString());Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath
28bubuko.com,布布扣
29bubuko.com,布布扣//Excel -〉Html(这个与Word不同,因为Excel为很多层,又并列很多层,必须都清空才能销毁实例,但实际中我发现并不是每次都能销毁,所以网上求解多次没有结果,只能杀没进程,为了保证只杀灭最近的进程,我用时间进行判断)
30bubuko.com,布布扣
31bubuko.com,布布扣Microsoft.Office.Interop.Excel.Application   repExcel   =   new   Microsoft.Office.Interop.Excel.Application ();//实例化Excel
32bubuko.com,布布扣Microsoft.Office.Interop.Excel.Workbook   workbook   =   null;         
33bubuko.com,布布扣Microsoft.Office.Interop.Excel.Worksheet worksheet   =   null;
34bubuko.com,布布扣workbook   =   repExcel.Application.Workbooks.Open();//打开文件,n.FullPath是文件路径
35bubuko.com,布布扣worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
36bubuko.com,布布扣object   htmlFile   =   Application.StartupPath+@"\ccyt_chm\inform\"+n.FullPath.Split(‘.‘).GetValue(0)+".html";   
37bubuko.com,布布扣object   ofmt   =   Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;   
38bubuko.com,布布扣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);//进行另存为操作   
39bubuko.com,布布扣object   osave   =   false;         
40bubuko.com,布布扣workbook.Close(osave,Type.Missing,Type.Missing);//逐步关闭所有使用的对象
41bubuko.com,布布扣repExcel.Quit();
42bubuko.com,布布扣System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
43bubuko.com,布布扣worksheet = null;
44bubuko.com,布布扣GC.Collect();//垃圾回收
45bubuko.com,布布扣System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
46bubuko.com,布布扣workbook=null;
47bubuko.com,布布扣GC.Collect();
48bubuko.com,布布扣System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
49bubuko.com,布布扣GC.Collect();
50bubuko.com,布布扣System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
51bubuko.com,布布扣repExcel = null;
52bubuko.com,布布扣GC.Collect();
53bubuko.com,布布扣System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");//依据时间杀灭进程
54bubuko.com,布布扣foreach ( System.Diagnostics.Process p in process)
55bubuko.com,布布扣{
56bubuko.com,布布扣     if (DateTime.Now.Second - p.StartTime.Second > 0 && DateTime.Now.Second - p.StartTime.Second < 5)
57bubuko.com,布布扣     {
58bubuko.com,布布扣           p.Kill();
59bubuko.com,布布扣      }
60bubuko.com,布布扣}
61bubuko.com,布布扣Thread.Sleep(3000);//保证完全关闭
62bubuko.com,布布扣StreamReader objreader = new StreamReader(htmlFile.ToString().Split(‘.‘).GetValue(0)+".files\\sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下内容是在Html的第一个框架中添加下载原Excel的超链接         
63bubuko.com,布布扣FileStream fs = new FileStream(htmlFile.ToString().Split(‘.‘).GetValue(0)+".files\\sheet001$.html",FileMode.Create);
64bubuko.com,布布扣streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
65bubuko.com,布布扣streamHtmlHelp.WriteLine("<a href=\""+"../"+n.Text+"\">源文件下载</a><br>");
66bubuko.com,布布扣do 
67bubuko.com,布布扣{
68bubuko.com,布布扣     str = objreader.ReadLine();
69bubuko.com,布布扣     streamHtmlHelp.WriteLine(str);
70bubuko.com,布布扣}
71bubuko.com,布布扣while (str != "</html>");
72bubuko.com,布布扣streamHtmlHelp.Close();
73bubuko.com,布布扣objreader.Close();
74bubuko.com,布布扣File.Delete(htmlFile.ToString().Split(‘.‘).GetValue(0)+".files\\sheet001.html");
75bubuko.com,布布扣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
76bubuko.com,布布扣

6.c# 实现Word联接Excel的MailMerge功能
bubuko.com,布布扣
  1bubuko.com,布布扣//目标:使用word的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。
  2bubuko.com,布布扣
  3bubuko.com,布布扣//关于Word的MailMerge功能:
  4bubuko.com,布布扣
  5bubuko.com,布布扣//word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。
  6bubuko.com,布布扣
  7bubuko.com,布布扣 
  8bubuko.com,布布扣
  9bubuko.com,布布扣//为了实现这个功能,我的程序要能做的是
 10bubuko.com,布布扣
 11bubuko.com,布布扣//1:打开word文件对象
 12bubuko.com,布布扣
 13bubuko.com,布布扣//2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s
 14bubuko.com,布布扣
 15bubuko.com,布布扣//3:关闭保存
 16bubuko.com,布布扣
 17bubuko.com,布布扣 
 18bubuko.com,布布扣
 19bubuko.com,布布扣//关于引用:
 20bubuko.com,布布扣
 21bubuko.com,布布扣using Word = Microsoft.Office.Interop.Word;
 22bubuko.com,布布扣
 23bubuko.com,布布扣using System.Reflection;
 24bubuko.com,布布扣
 25bubuko.com,布布扣using System.Diagnostics;
 26bubuko.com,布布扣
 27bubuko.com,布布扣using System.IO;
 28bubuko.com,布布扣
 29bubuko.com,布布扣//关于变量:word的com对象需要传入的参数定义
 30bubuko.com,布布扣
 31bubuko.com,布布扣Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
 32bubuko.com,布布扣
 33bubuko.com,布布扣object missing = System.Reflection.Missing.Value; 
 34bubuko.com,布布扣
 35bubuko.com,布布扣object falseValue = false;
 36bubuko.com,布布扣
 37bubuko.com,布布扣object trueValue = true;
 38bubuko.com,布布扣
 39bubuko.com,布布扣//关于处理
 40bubuko.com,布布扣
 41bubuko.com,布布扣//需要注重的是
 42bubuko.com,布布扣
 43bubuko.com,布布扣//1:打开word的方式
 44bubuko.com,布布扣
 45bubuko.com,布布扣//2:query的写法。类似于sql一般,比较好玩。
 46bubuko.com,布布扣
 47bubuko.com,布布扣//3:设置列,。设置之后,在word中可以看见这些列。
 48bubuko.com,布布扣
 49bubuko.com,布布扣//4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。
 50bubuko.com,布布扣
 51bubuko.com,布布扣private void button1_Click(object sender, EventArgs e)
 52bubuko.com,布布扣
 53bubuko.com,布布扣{
 54bubuko.com,布布扣
 55bubuko.com,布布扣object fileName = CopyTemplateDoc();//copy doc in
 56bubuko.com,布布扣
 57bubuko.com,布布扣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);
 58bubuko.com,布布扣
 59bubuko.com,布布扣object linkTo = CopyExcelData();//copy excel data
 60bubuko.com,布布扣
 61bubuko.com,布布扣object query = "SELECT * FROM `Sheet1$`";//data from sheet1
 62bubuko.com,布布扣
 63bubuko.com,布布扣object header = "Name,Category,Address,Content";//filed list
 64bubuko.com,布布扣
 65bubuko.com,布布扣try
 66bubuko.com,布布扣
 67bubuko.com,布布扣{
 68bubuko.com,布布扣
 69bubuko.com,布布扣doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
 70bubuko.com,布布扣
 71bubuko.com,布布扣doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
 72bubuko.com,布布扣
 73bubuko.com,布布扣MessageBox.Show("success");
 74bubuko.com,布布扣
 75bubuko.com,布布扣}
 76bubuko.com,布布扣
 77bubuko.com,布布扣catch (Exception ex)
 78bubuko.com,布布扣
 79bubuko.com,布布扣{
 80bubuko.com,布布扣
 81bubuko.com,布布扣MessageBox.Show(ex.Message);
 82bubuko.com,布布扣
 83bubuko.com,布布扣}
 84bubuko.com,布布扣
 85bubuko.com,布布扣finally
 86bubuko.com,布布扣
 87bubuko.com,布布扣{
 88bubuko.com,布布扣
 89bubuko.com,布布扣doc.Save();//save word
 90bubuko.com,布布扣
 91bubuko.com,布布扣CloseApp();//close word app
 92bubuko.com,布布扣
 93bubuko.com,布布扣CopyExcelData();//copy data again,*******************
 94bubuko.com,布布扣
 95bubuko.com,布布扣}
 96bubuko.com,布布扣
 97bubuko.com,布布扣}
 98bubuko.com,布布扣
 99bubuko.com,布布扣//关于关闭word对象
100bubuko.com,布布扣
101bubuko.com,布布扣public void CloseApp()
102bubuko.com,布布扣{
103bubuko.com,布布扣WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
104bubuko.com,布布扣WordApp.Quit(ref trueValue, ref missing, ref missing);
105bubuko.com,布布扣System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
106bubuko.com,布布扣GC.Collect();
107bubuko.com,布布扣
108bubuko.com,布布扣//this.KillExcelProcess();
109bubuko.com,布布扣}
110bubuko.com,布布扣
111bubuko.com,布布扣//还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
112bubuko.com,布布扣

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

8.c#读取Word
bubuko.com,布布扣
  1bubuko.com,布布扣//1:
  2bubuko.com,布布扣//对项目添加引用,Microsoft Word 11.0 Object //Library
  3bubuko.com,布布扣//2:
  4bubuko.com,布布扣//在程序中添加 using Word = Microsoft.Office.Interop.Word; 
  5bubuko.com,布布扣//3:
  6bubuko.com,布布扣//程序中添加
  7bubuko.com,布布扣Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序
  8bubuko.com,布布扣Word.Document doc = null; //一会要记录word打开的文档
  9bubuko.com,布布扣//word文档和word程序可不是一回事奥!
 10bubuko.com,布布扣4:
 11bubuko.com,布布扣//一般来说,对于抽取word内容,用的方法很少
 12bubuko.com,布布扣public override void openFile(object fileName){} //打开文档
 13bubuko.com,布布扣public override object readPar(int i){} //读取word文档的第i段
 14bubuko.com,布布扣public override int getParCount(){} //返回word文档一共几段
 15bubuko.com,布布扣public override void closeFile(){} //关闭文档
 16bubuko.com,布布扣public override void quit(){} //关闭word程序
 17bubuko.com,布布扣
 18bubuko.com,布布扣//从网页上拷贝的目录有时候会出现手动换行符^l,,先将其换成回车段落标记,才能正确读取
 19bubuko.com,布布扣public void replaceChar(){}
 20bubuko.com,布布扣
 21bubuko.com,布布扣5:代码
 22bubuko.com,布布扣
 23bubuko.com,布布扣public override void openFile(object fileName)
 24bubuko.com,布布扣        {
 25bubuko.com,布布扣            try
 26bubuko.com,布布扣            {
 27bubuko.com,布布扣                if (app.Documents.Count > 0)
 28bubuko.com,布布扣                {
 29bubuko.com,布布扣                    if (MessageBox.Show("已经打开了一个word文档,你想关闭重新打开该文档吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
 30bubuko.com,布布扣                    {
 31bubuko.com,布布扣                        object unknow = Type.Missing;
 32bubuko.com,布布扣                        doc = app.ActiveDocument;
 33bubuko.com,布布扣                        if (MessageBox.Show("你想保存吗?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
 34bubuko.com,布布扣                        {
 35bubuko.com,布布扣                            app.ActiveDocument.Save();
 36bubuko.com,布布扣                        }
 37bubuko.com,布布扣
 38bubuko.com,布布扣                        app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
 39bubuko.com,布布扣                        app.Visible = false;
 40bubuko.com,布布扣                    }
 41bubuko.com,布布扣                    else
 42bubuko.com,布布扣                    {
 43bubuko.com,布布扣                        return;
 44bubuko.com,布布扣                    }
 45bubuko.com,布布扣                }
 46bubuko.com,布布扣            }
 47bubuko.com,布布扣            catch (Exception)
 48bubuko.com,布布扣            {
 49bubuko.com,布布扣                //MessageBox.Show("您可能关闭了文档");
 50bubuko.com,布布扣                app = new Microsoft.Office.Interop.Word.Application();
 51bubuko.com,布布扣            }
 52bubuko.com,布布扣
 53bubuko.com,布布扣            try
 54bubuko.com,布布扣            {
 55bubuko.com,布布扣                object unknow = Type.Missing;
 56bubuko.com,布布扣                app.Visible = true;
 57bubuko.com,布布扣                doc = app.Documents.Open(ref fileName,
 58bubuko.com,布布扣                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
 59bubuko.com,布布扣                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
 60bubuko.com,布布扣                                         ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
 61bubuko.com,布布扣             }
 62bubuko.com,布布扣             catch (Exception ex)
 63bubuko.com,布布扣             {
 64bubuko.com,布布扣                 MessageBox.Show("出现错误:" + ex.ToString());
 65bubuko.com,布布扣             }   
 66bubuko.com,布布扣           
 67bubuko.com,布布扣        }
 68bubuko.com,布布扣public override object readPar(int i)
 69bubuko.com,布布扣        {
 70bubuko.com,布布扣            try
 71bubuko.com,布布扣            {
 72bubuko.com,布布扣                string temp = doc.Paragraphs[i].Range.Text.Trim();
 73bubuko.com,布布扣                return temp;
 74bubuko.com,布布扣            }
 75bubuko.com,布布扣            catch (Exception e) {
 76bubuko.com,布布扣                MessageBox.Show("Error:"+e.ToString());
 77bubuko.com,布布扣                return null;
 78bubuko.com,布布扣            }
 79bubuko.com,布布扣        }
 80bubuko.com,布布扣
 81bubuko.com,布布扣public override int getParCount()
 82bubuko.com,布布扣        {
 83bubuko.com,布布扣            return doc.Paragraphs.Count;
 84bubuko.com,布布扣        }
 85bubuko.com,布布扣
 86bubuko.com,布布扣public override void closeFile()
 87bubuko.com,布布扣        {
 88bubuko.com,布布扣            try
 89bubuko.com,布布扣            {
 90bubuko.com,布布扣                object unknow = Type.Missing;
 91bubuko.com,布布扣                object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
 92bubuko.com,布布扣                app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
 93bubuko.com,布布扣            }
 94bubuko.com,布布扣            catch (Exception ex)
 95bubuko.com,布布扣            {
 96bubuko.com,布布扣                MessageBox.Show("Error:" + ex.ToString());
 97bubuko.com,布布扣            }
 98bubuko.com,布布扣        }
 99bubuko.com,布布扣
100bubuko.com,布布扣public override void quit()
101bubuko.com,布布扣        {
102bubuko.com,布布扣            try
103bubuko.com,布布扣            {
104bubuko.com,布布扣                object unknow = Type.Missing;
105bubuko.com,布布扣                object saveChanges = Word.WdSaveOptions.wdSaveChanges;
106bubuko.com,布布扣                app.Quit(ref saveChanges, ref unknow, ref unknow);
107bubuko.com,布布扣            }
108bubuko.com,布布扣            catch (Exception)
109bubuko.com,布布扣            {
110bubuko.com,布布扣
111bubuko.com,布布扣            }
112bubuko.com,布布扣        }
113bubuko.com,布布扣
114bubuko.com,布布扣public void replaceChar() {
115bubuko.com,布布扣            try
116bubuko.com,布布扣            {
117bubuko.com,布布扣                object replaceAll = Word.WdReplace.wdReplaceAll;
118bubuko.com,布布扣                object missing = Type.Missing;
119bubuko.com,布布扣
120bubuko.com,布布扣                app.Selection.Find.ClearFormatting();
121bubuko.com,布布扣                app.Selection.Find.Text = "^l";
122bubuko.com,布布扣
123bubuko.com,布布扣                app.Selection.Find.Replacement.ClearFormatting();
124bubuko.com,布布扣                app.Selection.Find.Replacement.Text = "^p";
125bubuko.com,布布扣
126bubuko.com,布布扣                app.Selection.Find.Execute(
127bubuko.com,布布扣                    ref missing, ref missing, ref missing, ref missing, ref missing,
128bubuko.com,布布扣                    ref missing, ref missing, ref missing, ref missing, ref missing,
129bubuko.com,布布扣                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);
130bubuko.com,布布扣            }
131bubuko.com,布布扣            catch (Exception e)
132bubuko.com,布布扣            {
133bubuko.com,布布扣                MessageBox.Show("文档出现错误,请重新操作");
134bubuko.com,布布扣            }
135bubuko.com,布布扣        }
136bubuko.com,布布扣
137bubuko.com,布布扣//6:
138bubuko.com,布布扣//刚才是用读取一段做的例子,如果要读取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因为都是微软的东东,所以用起来没有一点的障碍,再加上现在的vs2005做的很智能,所以先从java转到了c#上
139bubuko.com,布布扣
140bubuko.com,布布扣//7:
141bubuko.com,布布扣//实际上,c#中读取word是不用那么麻烦的,但是如果考虑到可能还要抽取txt,ppt等多种格式,所以就写了一个抽象类,调用起来也方便,这就是为什么我的程序方法开头会有override的原因,总要考虑到通用,所以多了一些代码。
142bubuko.com,布布扣
143bubuko.com,布布扣

9.C#打开WORD文档内容并显示
bubuko.com,布布扣
 1bubuko.com,布布扣private void button1_Click(object sender, System.EventArgs e)
 2bubuko.com,布布扣   {
 3bubuko.com,布布扣    //调用打开文件对话框获取要打开的文件WORD文件,RTF文件,文本文件路径名称
 4bubuko.com,布布扣    OpenFileDialog opd = new OpenFileDialog();
 5bubuko.com,布布扣    opd.InitialDirectory = "c:\\";
 6bubuko.com,布布扣    opd.Filter = "Word文档(*.doc)|*.doc|文本文档(*.txt)|*.txt|RTF文档(*.rtf)|*.rtf|所有文档(*.*)|*.*";
 7bubuko.com,布布扣    opd.FilterIndex = 1;
 8bubuko.com,布布扣   
 9bubuko.com,布布扣    if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
10bubuko.com,布布扣    {   
11bubuko.com,布布扣   
12bubuko.com,布布扣     //建立Word类的实例,缺点:不能正确读取表格,图片等等的显示
13bubuko.com,布布扣     Word.ApplicationClass app = new Word.ApplicationClass();
14bubuko.com,布布扣     Word.Document doc = null;
15bubuko.com,布布扣     object missing = System.Reflection.Missing.Value;
16bubuko.com,布布扣
17bubuko.com,布布扣     object FileName = opd.FileName;
18bubuko.com,布布扣     object readOnly = false;
19bubuko.com,布布扣     object isVisible = true;
20bubuko.com,布布扣     object index = 0;
21bubuko.com,布布扣     try
22bubuko.com,布布扣     {
23bubuko.com,布布扣      doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
24bubuko.com,布布扣       ref missing, ref missing, ref missing, ref missing, ref missing,
25bubuko.com,布布扣       ref missing, ref missing, ref missing, ref isVisible, ref missing,
26bubuko.com,布布扣       ref missing, ref missing, ref missing);
27bubuko.com,布布扣
28bubuko.com,布布扣      doc.ActiveWindow.Selection.WholeStory();
29bubuko.com,布布扣      doc.ActiveWindow.Selection.Copy(); 
30bubuko.com,布布扣      //从剪切板获取数据
31bubuko.com,布布扣      IDataObject data=Clipboard.GetDataObject();
32bubuko.com,布布扣      this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
33bubuko.com,布布扣      
34bubuko.com,布布扣     }
35bubuko.com,布布扣     finally
36bubuko.com,布布扣     {
37bubuko.com,布布扣      if (doc != null)
38bubuko.com,布布扣      {
39bubuko.com,布布扣       doc.Close(ref missing, ref missing, ref missing);
40bubuko.com,布布扣       doc = null;
41bubuko.com,布布扣      }
42bubuko.com,布布扣
43bubuko.com,布布扣      if (app != null)
44bubuko.com,布布扣      {
45bubuko.com,布布扣       app.Quit(ref missing, ref missing, ref missing);
46bubuko.com,布布扣       app = null;
47bubuko.com,布布扣      }
48bubuko.com,布布扣     }
49bubuko.com,布布扣
50bubuko.com,布布扣    }
51bubuko.com,布布扣
52bubuko.com,布布扣   }

C# Word,布布扣,bubuko.com

C# Word

标签:style   blog   http   color   java   使用   os   io   

原文地址:http://www.cnblogs.com/net-study/p/3907720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!