1.c#操作word 在指定书签插入文字或者图片
2.C#替换Word模版中的标签内容的例子
3.用C#实现在Word文档中搜索文本
4.C#动态生成Word文档并填充数据
5.C# 将Word,Excel转换成Html
6.c# 实现Word联接Excel的MailMerge功能
7.c#操作word表格
8 .c#读取Word
9.C#打开WORD文档内容并显示
Code
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
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
1// open
2object omissing = system.reflection.missing.value;
3word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass();
4object readonly = false;
5object template = templatepath;
6word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly,
7ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing,
8ref omissing, ref omissing, ref omissing,ref omissing,ref omissing,ref omissing,ref omissing);
9// modify
10for (int i = 1; i <= doc.bookmarks.count; i++)
11{
12object j = i;
13word.range wordrng = doc.bookmarks.get_item(ref j).range;
14wordrng.text = "这是第" + i + "个标签,名称为" + doc.bookmarks.get_item(ref j).name;
15}
16
17// save
18object savefilename = mappath(request.applicationpath + "/document") + "/" + guid.newguid().tostring() + ".doc";
19doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,
20ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing);
21doc.close( ref omissing, ref omissing, ref omissing );
22wordapp.quit( ref omissing, ref omissing, ref omissing );
23
24
1// open
2object omissing = system.reflection.missing.value;
3word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass();
4object readonly = false;
5object template = templatepath;
6word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly,
7ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing,
8ref omissing, ref omissing, ref omissing,ref omissing,ref omissing,ref omissing,ref omissing);
9// modify
10for (int i = 1; i <= doc.bookmarks.count; i++)
11{
12object j = i;
13word.range wordrng = doc.bookmarks.get_item(ref j).range;
14wordrng.text = "这是第" + i + "个标签,名称为" + doc.bookmarks.get_item(ref j).name;
15}
16
17// save
18object savefilename = mappath(request.applicationpath + "/document") + "/" + guid.newguid().tostring() + ".doc";
19doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,
20ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing);
21doc.close( ref omissing, ref omissing, ref omissing );
22wordapp.quit( ref omissing, ref omissing, ref omissing );
23
24
3.用C#实现在Word文档中搜索文本
Code
1object filename=""; //要打开的文档路径
2string strKey=""; //要搜索的文本
3object MissingValue=Type.Missing;
4
5Word.Application wp=new Word.ApplicationClass();
6Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
7 ref MissingValue,ref MissingValue,
8 ref MissingValue,ref MissingValue,
9 ref MissingValue,ref MissingValue,
10 ref MissingValue,ref MissingValue,
11 ref MissingValue,ref MissingValue,
12 ref MissingValue,ref MissingValue,
13 ref MissingValue,ref MissingValue);
14int i=0,iCount=0;
15Word.Find wfnd;
16
17if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
18{
19 iCount=wd.Paragraphs.Count;
20 for(i=1;i<=iCount;i++)
21{
22 wfnd=wd.Paragraphs[i].Range.Find;
23 wfnd.ClearFormatting();
24 wfnd.Text=strKey;
25 if (wfnd.Execute(ref MissingValue,ref MissingValue,
26 ref MissingValue,ref MissingValue,
27 ref MissingValue,ref MissingValue,
28 ref MissingValue,ref MissingValue,
29 ref MissingValue,ref MissingValue,
30 ref MissingValue,ref MissingValue,
31 ref MissingValue,ref MissingValue,
32 ref MissingValue))
33 {
34 MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
35 break;
36 }
37 }
38}
39
40
41
1object filename=""; //要打开的文档路径
2string strKey=""; //要搜索的文本
3object MissingValue=Type.Missing;
4
5Word.Application wp=new Word.ApplicationClass();
6Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
7 ref MissingValue,ref MissingValue,
8 ref MissingValue,ref MissingValue,
9 ref MissingValue,ref MissingValue,
10 ref MissingValue,ref MissingValue,
11 ref MissingValue,ref MissingValue,
12 ref MissingValue,ref MissingValue,
13 ref MissingValue,ref MissingValue);
14int i=0,iCount=0;
15Word.Find wfnd;
16
17if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
18{
19 iCount=wd.Paragraphs.Count;
20 for(i=1;i<=iCount;i++)
21{
22 wfnd=wd.Paragraphs[i].Range.Find;
23 wfnd.ClearFormatting();
24 wfnd.Text=strKey;
25 if (wfnd.Execute(ref MissingValue,ref MissingValue,
26 ref MissingValue,ref MissingValue,
27 ref MissingValue,ref MissingValue,
28 ref MissingValue,ref MissingValue,
29 ref MissingValue,ref MissingValue,
30 ref MissingValue,ref MissingValue,
31 ref MissingValue,ref MissingValue,
32 ref MissingValue))
33 {
34 MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
35 break;
36 }
37 }
38}
39
40
41
4.C#动态生成Word文档并填充数据
Code
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, 12, 3, ref 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(1, 1).Range.Text = "产品详细信息表";
59 newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
60 //合并单元格
61 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
62 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
63 WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
64
65 //填充表格内容
66 newTable.Cell(2, 1).Range.Text = "产品基本信息";
67 newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
68 //合并单元格
69 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
70 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
71
72 //填充表格内容
73 newTable.Cell(3, 1).Range.Text = "品牌名称:";
74 newTable.Cell(3, 2).Range.Text = "BrandName";
75 //纵向合并单元格
76 newTable.Cell(3, 3).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(12, 1).Range.Text = "产品特殊属性";
95 newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
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
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, 12, 3, ref 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(1, 1).Range.Text = "产品详细信息表";
59 newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
60 //合并单元格
61 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
62 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
63 WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
64
65 //填充表格内容
66 newTable.Cell(2, 1).Range.Text = "产品基本信息";
67 newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
68 //合并单元格
69 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
70 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
71
72 //填充表格内容
73 newTable.Cell(3, 1).Range.Text = "品牌名称:";
74 newTable.Cell(3, 2).Range.Text = "BrandName";
75 //纵向合并单元格
76 newTable.Cell(3, 3).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(12, 1).Range.Text = "产品特殊属性";
95 newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
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
1//Word -〉Html
2
3Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//实例化一个Word
4Type wordtype = appclass.GetType();
5Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//获取Document
6Type docstype = docs.GetType();
7object filename = ;//n.FullPath为Word文件的路径
8Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docstype.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,new object[]{filename,true,true});//打开文件
9Type doctype = doc.GetType();
10object savefilename = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
11doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存为Html格式
12wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出
13Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒
14StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312")); //以下内容是为了在Html中加入对本身Word文件的下载
15FileStream fs = new FileStream(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",FileMode.Create);
16streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
17streamHtmlHelp.WriteLine("<a href=/""+n.Text+"/">源文件下载</a><br>");
18do
19{
20 str = objreader.ReadLine();
21 streamHtmlHelp.WriteLine(str);
22}
23while (str != "</html>");
24streamHtmlHelp.Close();
25objreader.Close();
26File.Delete(savefilename.ToString());
27File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",savefilename.ToString());Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath
28
29//Excel -〉Html(这个与Word不同,因为Excel为很多层,又并列很多层,必须都清空才能销毁实例,但实际中我发现并不是每次都能销毁,所以网上求解多次没有结果,只能杀没进程,为了保证只杀灭最近的进程,我用时间进行判断)
30
31Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application ();//实例化Excel
32Microsoft.Office.Interop.Excel.Workbook workbook = null;
33Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
34workbook = repExcel.Application.Workbooks.Open();//打开文件,n.FullPath是文件路径
35worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
36object htmlFile = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
37object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
38workbook.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);//进行另存为操作
39object osave = false;
40workbook.Close(osave,Type.Missing,Type.Missing);//逐步关闭所有使用的对象
41repExcel.Quit();
42System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
43worksheet = null;
44GC.Collect();//垃圾回收
45System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
46workbook=null;
47GC.Collect();
48System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
49GC.Collect();
50System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
51repExcel = null;
52GC.Collect();
53System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");//依据时间杀灭进程
54foreach ( System.Diagnostics.Process p in process)
55{
56 if (DateTime.Now.Second - p.StartTime.Second > 0 && DateTime.Now.Second - p.StartTime.Second < 5)
57 {
58 p.Kill();
59 }
60}
61Thread.Sleep(3000);//保证完全关闭
62StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下内容是在Html的第一个框架中添加下载原Excel的超链接
63FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001$.html",FileMode.Create);
64streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
65streamHtmlHelp.WriteLine("<a href=/""+"../"+n.Text+"/">源文件下载</a><br>");
66do
67{
68 str = objreader.ReadLine();
69 streamHtmlHelp.WriteLine(str);
70}
71while (str != "</html>");
72streamHtmlHelp.Close();
73objreader.Close();
74File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html");
75File.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
76
1//Word -〉Html
2
3Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//实例化一个Word
4Type wordtype = appclass.GetType();
5Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//获取Document
6Type docstype = docs.GetType();
7object filename = ;//n.FullPath为Word文件的路径
8Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docstype.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,new object[]{filename,true,true});//打开文件
9Type doctype = doc.GetType();
10object savefilename = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
11doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存为Html格式
12wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出
13Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒
14StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312")); //以下内容是为了在Html中加入对本身Word文件的下载
15FileStream fs = new FileStream(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",FileMode.Create);
16streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
17streamHtmlHelp.WriteLine("<a href=/""+n.Text+"/">源文件下载</a><br>");
18do
19{
20 str = objreader.ReadLine();
21 streamHtmlHelp.WriteLine(str);
22}
23while (str != "</html>");
24streamHtmlHelp.Close();
25objreader.Close();
26File.Delete(savefilename.ToString());
27File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",savefilename.ToString());Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath
28
29//Excel -〉Html(这个与Word不同,因为Excel为很多层,又并列很多层,必须都清空才能销毁实例,但实际中我发现并不是每次都能销毁,所以网上求解多次没有结果,只能杀没进程,为了保证只杀灭最近的进程,我用时间进行判断)
30
31Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application ();//实例化Excel
32Microsoft.Office.Interop.Excel.Workbook workbook = null;
33Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
34workbook = repExcel.Application.Workbooks.Open();//打开文件,n.FullPath是文件路径
35worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
36object htmlFile = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
37object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
38workbook.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);//进行另存为操作
39object osave = false;
40workbook.Close(osave,Type.Missing,Type.Missing);//逐步关闭所有使用的对象
41repExcel.Quit();
42System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
43worksheet = null;
44GC.Collect();//垃圾回收
45System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
46workbook=null;
47GC.Collect();
48System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
49GC.Collect();
50System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
51repExcel = null;
52GC.Collect();
53System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");//依据时间杀灭进程
54foreach ( System.Diagnostics.Process p in process)
55{
56 if (DateTime.Now.Second - p.StartTime.Second > 0 && DateTime.Now.Second - p.StartTime.Second < 5)
57 {
58 p.Kill();
59 }
60}
61Thread.Sleep(3000);//保证完全关闭
62StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下内容是在Html的第一个框架中添加下载原Excel的超链接
63FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001$.html",FileMode.Create);
64streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
65streamHtmlHelp.WriteLine("<a href=/""+"../"+n.Text+"/">源文件下载</a><br>");
66do
67{
68 str = objreader.ReadLine();
69 streamHtmlHelp.WriteLine(str);
70}
71while (str != "</html>");
72streamHtmlHelp.Close();
73objreader.Close();
74File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html");
75File.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
76
6.c# 实现Word联接Excel的MailMerge功能
Code
1//目标:使用word的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。
2
3//关于Word的MailMerge功能:
4
5//word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。
6
7
8
9//为了实现这个功能,我的程序要能做的是
10
11//1:打开word文件对象
12
13//2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s
14
15//3:关闭保存
16
17
18
19//关于引用:
20
21using Word = Microsoft.Office.Interop.Word;
22
23using System.Reflection;
24
25using System.Diagnostics;
26
27using System.IO;
28
29//关于变量:word的com对象需要传入的参数定义
30
31Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
32
33object missing = System.Reflection.Missing.Value;
34
35object falseValue = false;
36
37object trueValue = true;
38
39//关于处理
40
41//需要注重的是
42
43//1:打开word的方式
44
45//2:query的写法。类似于sql一般,比较好玩。
46
47//3:设置列,。设置之后,在word中可以看见这些列。
48
49//4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。
50
51private void button1_Click(object sender, EventArgs e)
52
53{
54
55object fileName = CopyTemplateDoc();//copy doc in
56
57Word.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);
58
59object linkTo = CopyExcelData();//copy excel data
60
61object query = "SELECT * FROM `Sheet1$`";//data from sheet1
62
63object header = "Name,Category,Address,Content";//filed list
64
65try
66
67{
68
69doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
70
71doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
72
73MessageBox.Show("success");
74
75}
76
77catch (Exception ex)
78
79{
80
81MessageBox.Show(ex.Message);
82
83}
84
85finally
86
87{
88
89doc.Save();//save word
90
91CloseApp();//close word app
92
93CopyExcelData();//copy data again,*******************
94
95}
96
97}
98
99//关于关闭word对象
100
101public void CloseApp()
102{
103WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
104WordApp.Quit(ref trueValue, ref missing, ref missing);
105System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
106GC.Collect();
107
108//this.KillExcelProcess();
109}
110
111//还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
112
1//目标:使用word的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。
2
3//关于Word的MailMerge功能:
4
5//word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。
6
7
8
9//为了实现这个功能,我的程序要能做的是
10
11//1:打开word文件对象
12
13//2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s
14
15//3:关闭保存
16
17
18
19//关于引用:
20
21using Word = Microsoft.Office.Interop.Word;
22
23using System.Reflection;
24
25using System.Diagnostics;
26
27using System.IO;
28
29//关于变量:word的com对象需要传入的参数定义
30
31Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
32
33object missing = System.Reflection.Missing.Value;
34
35object falseValue = false;
36
37object trueValue = true;
38
39//关于处理
40
41//需要注重的是
42
43//1:打开word的方式
44
45//2:query的写法。类似于sql一般,比较好玩。
46
47//3:设置列,。设置之后,在word中可以看见这些列。
48
49//4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。
50
51private void button1_Click(object sender, EventArgs e)
52
53{
54
55object fileName = CopyTemplateDoc();//copy doc in
56
57Word.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);
58
59object linkTo = CopyExcelData();//copy excel data
60
61object query = "SELECT * FROM `Sheet1$`";//data from sheet1
62
63object header = "Name,Category,Address,Content";//filed list
64
65try
66
67{
68
69doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
70
71doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
72
73MessageBox.Show("success");
74
75}
76
77catch (Exception ex)
78
79{
80
81MessageBox.Show(ex.Message);
82
83}
84
85finally
86
87{
88
89doc.Save();//save word
90
91CloseApp();//close word app
92
93CopyExcelData();//copy data again,*******************
94
95}
96
97}
98
99//关于关闭word对象
100
101public void CloseApp()
102{
103WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
104WordApp.Quit(ref trueValue, ref missing, ref missing);
105System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
106GC.Collect();
107
108//this.KillExcelProcess();
109}
110
111//还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
112
7.c#操作word表格
Code
1//对word中表格的操作,以下是部分代码,关于操作不规则表格的.
2using System;
3using System.Collections;
4using System.ComponentModel;
5using System.Data;
6using System.Drawing;
7using System.Web;
8using System.Web.SessionState;
9using System.Web.UI;
10using System.Web.UI.WebControls;
11using System.Web.UI.HtmlControls;
12using System.Configuration;
13using System.IO;
14
15using System.Reflection;
16using System.Runtime.InteropServices ;
17using System.Threading;
18
19public void MakeMyTable(DataTable DT,string strFilePath)
20 {
21
22 string strEnd = this.txtEnd.Text.Trim().ToString();
23 string strStart = this.txtStart.Text.Trim().ToString();
24//生成文档分页中的起始和终止页
25 string strSign = "("+strStart + "-" + strEnd + ")";
26
27 //杀掉所有word进程以保证速度
28 //KillWordProcess();
29
30 object Nothing = System.Reflection.Missing.Value;
31 object missing = System.Reflection.Missing.Value;
32 object filename= strFilePath;
33
34 Word.Application wordApp=new Word.ApplicationClass();
35 Word.Document wordDoc=wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
36
37 try
38 {
39 //生成过程中屏蔽返回按扭,不允许中途停止
40 Button2.Enabled = false;
41 生成文档#region 生成文档
42 //设置文档宽度
43 wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));
44 wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11 ;
45 wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));
46
47 Object start = Type.Missing;
48 Object end = Type.Missing;
49 Object unit = Type.Missing;
50 Object count = Type.Missing;
51 wordDoc.Range(ref start, ref end).Delete(ref unit, ref count);
52
53
54 object rng = Type.Missing;
55 string strInfo = this.txtNameCh.Text.ToString()+"明细表"+strSign+"/r/n";
56 start = 0;
57 end = 0;
58 wordDoc.Range(ref start, ref end).InsertBefore(strInfo);
59 wordDoc.Range(ref start, ref end).Font.Name = "Verdana";
60 wordDoc.Range(ref start, ref end).Font.Size = 20;
61 wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
62
63 start = 8;
64 end = strInfo.Length;
65 wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车
66
67 if(DT.Rows.Count>0)
68 {
69 //存在数据项
70 //添加一个表格
71 object missingValue = Type.Missing;
72 object location = strInfo.Length; //注:若location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
73 Word.Range rng2 = wordDoc.Range(ref location, ref location);
74
75 wordDoc.Tables.Add(rng2, 13, 6, ref missingValue, ref missingValue);
76 wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
77 wordDoc.Tables.Item(1).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
78 wordDoc.Tables.Item(1).Range.Font.Size = 10;
79 wordDoc.Tables.Item(1).Range.Font.Name = "宋体";
80 wordDoc.Tables.Item(1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
81 wordDoc.Tables.Item(1).Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
82 //设置表格样式
83 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
84 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
85 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic;
86
87 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
88 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
89 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorAutomatic;
90
91 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
92 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
93 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).Color = Word.WdColor.wdColorAutomatic;
94
95 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
96 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
97 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).Color = Word.WdColor.wdColorAutomatic;
98
99 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
100 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
101 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).Color = Word.WdColor.wdColorAutomatic;
102
103 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
104 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
105 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).Color = Word.WdColor.wdColorAutomatic;
106
107 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
108 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
109 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).Color = Word.WdColor.wdColorAutomatic;
110 //第一行显示
111 wordDoc.Tables.Item(1).Cell(1,2).Merge(wordDoc.Tables.Item(1).Cell(1,3));
112 wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(1,5));
113
114 //第二行显示
115 wordDoc.Tables.Item(1).Cell(2,5).Merge(wordDoc.Tables.Item(1).Cell(2,6));
116 wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(2,5));
117
118 插入数据行#region 插入数据行
119 wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "cell11";
120 //wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["cell11"].ToString();
121
122
123
124 /**/////******************
125 wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "cell13";
126 //wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["cell13"].ToString();
127
128
129
130 /**/////******************
131 wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "cell21";
132 //wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["cell21"].ToString();
133
134
135 /**/////******************
136 wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "cell23";
137 //wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["cell23"].ToString();
138
139 #endregion
140
141
142 第三行显示#region 第三行显示
143 wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
144 wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
145
146 /**/////******************
147 wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "cell31";
148
149
150
151
152
153 /**/////******************
154 wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "cell33";
155
156
157 #endregion
158
159
160 第五行显示#region 第五行显示
161 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
162 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
163 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
164 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
165 #endregion
166
167
168 第四行显示#region 第四行显示
169
170 /**/////******************
171 wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "cell41";
172
173
174
175
176 /**/////******************
177 wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "cell43";
178
179
180
181
182 /**/////******************
183 wordDoc.Tables.Item(1).Cell(4, 5).Range.Text = "cell45";
184
185 #endregion
186
187
188 第六行显示#region 第六行显示
189 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
190 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
191 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
192 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
193
194
195 /**/////******************
196 wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "cell51";
197
198 wordDoc.Tables.Item(1).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
199
200
201
202 /**/////******************
203 wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "cdll61";
204
205 wordDoc.Tables.Item(1).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
206 #endregion
207
208
209 第七行显示#region 第七行显示
210 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
211 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
212 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
213 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
214
215 /**/////******************
216 wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "cell71";
217
218 wordDoc.Tables.Item(1).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
219 #endregion
220
221
222 第八行显示#region 第八行显示
223 wordDoc.Tables.Item(1).Cell(8,1).Merge(wordDoc.Tables.Item(1).Cell(8,2));
224 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
225 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
226 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
227
228
229 #endregion
230
231
232 第九行显示#region 第九行显示
233 wordDoc.Tables.Item(1).Cell(9,1).Merge(wordDoc.Tables.Item(1).Cell(9,2));
234 wordDoc.Tables.Item(1).Cell(9,3).Merge(wordDoc.Tables.Item(1).Cell(9,4));
235
236 /**/////******************
237 wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "cell91";
238 //wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["cell91"].ToString()=="1"?"有":"无");
239
240
241
242
243 /**/////******************
244 wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "cell93";
245
246 #endregion
247
248
249 第十行显示#region 第十行显示
250 wordDoc.Tables.Item(1).Cell(10,1).Merge(wordDoc.Tables.Item(1).Cell(10,2));
251 wordDoc.Tables.Item(1).Cell(10,3).Merge(wordDoc.Tables.Item(1).Cell(10,4));
252 /**/////******************
253 wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "cell101";
254
255
256
257
258 /**/////******************
259 wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "cdll103";
260 //wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["Label"].ToString()=="1"?"有":"无");
261 #endregion
262
263
264 第十一行显示#region 第十一行显示
265 wordDoc.Tables.Item(1).Cell(11,1).Merge(wordDoc.Tables.Item(1).Cell(11,2));
266 wordDoc.Tables.Item(1).Cell(11,3).Merge(wordDoc.Tables.Item(1).Cell(11,4));
267 /**/////******************
268 wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "cell111";
269
270
271
272 /**/////******************
273 wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "cell113";
274
275 #endregion
276
277
278 第十二行显示#region 第十二行显示
279 wordDoc.Tables.Item(1).Cell(12,1).Merge(wordDoc.Tables.Item(1).Cell(12,2));
280 wordDoc.Tables.Item(1).Cell(12,3).Merge(wordDoc.Tables.Item(1).Cell(12,4));
281 /**/////******************
282 wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "cell121";
283
284
285 /**/////******************
286 wordDoc.Tables.Item(1).Cell(12, 3).Range.Text = "cell123";
287
288 #endregion
289
290
291 第十三行显示#region 第十三行显示
292 wordDoc.Tables.Item(1).Cell(13,1).Merge(wordDoc.Tables.Item(1).Cell(13,2));
293 wordDoc.Tables.Item(1).Cell(13,3).Merge(wordDoc.Tables.Item(1).Cell(13,4));
294
295 /**/////******************
296 wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "cell131";
297
298
299 /**/////******************
300 wordDoc.Tables.Item(1).Cell(13, 3).Range.Text = "cell133";
301
302 #endregion
303
304 wordDoc.Tables.Item(1).Select();
305 wordApp.Application.Selection.Cut();
306
307 //重新成声所有表
308
309
310
311
312 for(int i = 0; i<=DT.Rows.Count-1;i++)
313 {
314 wordApp.Application.Selection.Paste();
315 int k = i+1;
316 更新数据#region 更新数据
317
318
319 插入数据行#region 插入数据行
320
321 wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["1"].ToString();
322
323
324
325 /**/////******************
326
327 wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["2"].ToString();
328
329
330
331 /**/////******************
332
333 wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["3"].ToString();
334
335
336 /**/////******************
337
338 wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["4"].ToString();
339
340 #endregion
341
342
343 第三行显示#region 第三行显示
344 /**/////******************
345
346 wordDoc.Tables.Item(k).Cell(3, 2).Range.Text = DT.Rows[i]["5"].ToString();
347 /**/////******************
348
349 wordDoc.Tables.Item(k).Cell(3, 4).Range.Text = DT.Rows[i]["6"].ToString();
350
351 #endregion
352
353
354 第五行显示#region 第五行显示
355 /**/////******************
356
357 wordDoc.Tables.Item(k).Cell(5, 2).Range.Text = DT.Rows[i]["7"].ToString();
358 wordDoc.Tables.Item(k).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
359 #endregion
360
361 第四行显示#region 第四行显示
362
363 /**/////******************
364
365 wordDoc.Tables.Item(k).Cell(4, 2).Range.Text = DT.Rows[i]["8"].ToString();
366
367
368
369 /**/////******************
370
371 wordDoc.Tables.Item(k).Cell(4, 4).Range.Text = DT.Rows[i]["9"].ToString();
372
373
374
375 /**/////******************
376
377 wordDoc.Tables.Item(k).Cell(4, 6).Range.Text = DT.Rows[i]["0"].ToString();
378 #endregion
379
380
381 第六行显示#region 第六行显示
382 /**/////******************
383
384 wordDoc.Tables.Item(k).Cell(6, 2).Range.Text = DT.Rows[i]["11"].ToString();
385 wordDoc.Tables.Item(k).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
386 #endregion
387
388
389 第七行显示#region 第七行显示
390 /**/////******************
391
392 wordDoc.Tables.Item(k).Cell(7, 2).Range.Text = DT.Rows[i]["12"].ToString();
393 wordDoc.Tables.Item(k).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
394 #endregion
395
396
397 第八行显示#region 第八行显示
398 /**/////******************
399
400 string strTechlevel = DT.Rows[i]["Level"].ToString();
401 string returnTechlevel = "";
402 switch(strTechlevel)
403 {
404 case "1":
405 returnTechlevel = "Level1";
406 break;
407 case "2":
408 returnTechlevel = "Level2";
409 break;
410 case "3":
411 returnTechlevel = "Level3";
412 break;
413 case "0":
414 returnTechlevel = "Level4";
415 break;
416 default:
417 returnTechlevel = "Level5";
418 break;
419 }
420 wordDoc.Tables.Item(k).Cell(8, 2).Range.Text = returnTechlevel;
421
422 #endregion
423
424
425 第九行显示#region 第九行显示
426 /**/////******************
427
428 wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["14"].ToString()=="1"?"有":"无");
429
430
431
432
433 /**/////******************
434
435 wordDoc.Tables.Item(k).Cell(9, 4).Range.Text = (DT.Rows[i]["15"].ToString()=="1"?"是":"否");
436 #endregion
437
438
439 第十行显示#region 第十行显示
440 /**/////******************
441
442 wordDoc.Tables.Item(k).Cell(10, 2).Range.Text = (DT.Rows[i]["16"].ToString()=="1"?"有":"无");
443
444
445
446 /**/////******************
447
448 wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["17"].ToString()=="1"?"有":"无");
449 #endregion
450
451
452 第十一行显示#region 第十一行显示
453
454 /**/////******************
455
456 wordDoc.Tables.Item(k).Cell(11, 2).Range.Text = (DT.Rows[i]["18"].ToString()=="1"?"是":"否");
457
458
459 /**/////******************
460
461 wordDoc.Tables.Item(k).Cell(11, 4).Range.Text = (DT.Rows[i]["19"].ToString()=="1"?"是":"否");
462 #endregion
463
464
465 第十二行显示#region 第十二行显示
466 /**/////******************
467
468 wordDoc.Tables.Item(k).Cell(12, 2).Range.Text = (DT.Rows[i]["20"].ToString()=="1"?"是":"否");
469
470 /**/////******************
471
472 wordDoc.Tables.Item(k).Cell(12, 4).Range.Text = (DT.Rows[i]["21"].ToString()=="1"?"是":"否");
473 #endregion
474
475
476 第十三行显示#region 第十三行显示
477
478
479 wordDoc.Tables.Item(k).Cell(13, 2).Range.Text = (DT.Rows[i]["22"].ToString()=="1"?"是":"否");
480
481 /**/////******************
482
483 wordDoc.Tables.Item(k).Cell(13, 4).Range.Text = (DT.Rows[i]["23"].ToString()=="1"?"是":"否");
484 #endregion
485
486 #endregion
487
488 //插入分页
489 if(i!=DT.Rows.Count-1)
490 {
491 object mymissing = System.Reflection.Missing.Value;
492 object myunit = Word.WdUnits.wdStory;
493 wordApp.Selection.EndKey(ref myunit,ref mymissing);
494
495 object pBreak= (int)Word.WdBreakType.wdPageBreak;
496 wordApp.Selection.InsertBreak( ref pBreak );
497 }
498 }
499
500
501 wordDoc.SaveAs(ref filename, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing, ref missing);
502
503
504 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
505 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
506
507 if ( wordDoc != null )
508 {
509 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
510 wordDoc = null;
511 }
512 if ( wordApp != null )
513 {
514 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
515 wordApp = null;
516 }
517 GC.Collect();
518 //KillWordProcess();
519 string strUrl = "MakeWordFile.aspx?username="+Request.QueryString["username"].ToString();
520 utility.ShowPopMessage("文档生成完毕!",strUrl);
521 }
522 else
523 {
524 utility.ShowPopMessage("无任何数据!");
525 }
526 #endregion
527
528
529
530 }
531 catch
532 {
533 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
534 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
535 if ( wordDoc != null )
536 {
537 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
538 wordDoc = null;
539 }
540 if ( wordApp != null )
541 {
542 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
543 wordApp = null;
544 }
545 GC.Collect();
546 utility.ShowPopMessage("文档生成失败!");
547
548 }
549 }
550
551
1//对word中表格的操作,以下是部分代码,关于操作不规则表格的.
2using System;
3using System.Collections;
4using System.ComponentModel;
5using System.Data;
6using System.Drawing;
7using System.Web;
8using System.Web.SessionState;
9using System.Web.UI;
10using System.Web.UI.WebControls;
11using System.Web.UI.HtmlControls;
12using System.Configuration;
13using System.IO;
14
15using System.Reflection;
16using System.Runtime.InteropServices ;
17using System.Threading;
18
19public void MakeMyTable(DataTable DT,string strFilePath)
20 {
21
22 string strEnd = this.txtEnd.Text.Trim().ToString();
23 string strStart = this.txtStart.Text.Trim().ToString();
24//生成文档分页中的起始和终止页
25 string strSign = "("+strStart + "-" + strEnd + ")";
26
27 //杀掉所有word进程以保证速度
28 //KillWordProcess();
29
30 object Nothing = System.Reflection.Missing.Value;
31 object missing = System.Reflection.Missing.Value;
32 object filename= strFilePath;
33
34 Word.Application wordApp=new Word.ApplicationClass();
35 Word.Document wordDoc=wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
36
37 try
38 {
39 //生成过程中屏蔽返回按扭,不允许中途停止
40 Button2.Enabled = false;
41 生成文档#region 生成文档
42 //设置文档宽度
43 wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));
44 wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11 ;
45 wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));
46
47 Object start = Type.Missing;
48 Object end = Type.Missing;
49 Object unit = Type.Missing;
50 Object count = Type.Missing;
51 wordDoc.Range(ref start, ref end).Delete(ref unit, ref count);
52
53
54 object rng = Type.Missing;
55 string strInfo = this.txtNameCh.Text.ToString()+"明细表"+strSign+"/r/n";
56 start = 0;
57 end = 0;
58 wordDoc.Range(ref start, ref end).InsertBefore(strInfo);
59 wordDoc.Range(ref start, ref end).Font.Name = "Verdana";
60 wordDoc.Range(ref start, ref end).Font.Size = 20;
61 wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
62
63 start = 8;
64 end = strInfo.Length;
65 wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车
66
67 if(DT.Rows.Count>0)
68 {
69 //存在数据项
70 //添加一个表格
71 object missingValue = Type.Missing;
72 object location = strInfo.Length; //注:若location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
73 Word.Range rng2 = wordDoc.Range(ref location, ref location);
74
75 wordDoc.Tables.Add(rng2, 13, 6, ref missingValue, ref missingValue);
76 wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
77 wordDoc.Tables.Item(1).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
78 wordDoc.Tables.Item(1).Range.Font.Size = 10;
79 wordDoc.Tables.Item(1).Range.Font.Name = "宋体";
80 wordDoc.Tables.Item(1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
81 wordDoc.Tables.Item(1).Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
82 //设置表格样式
83 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
84 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
85 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic;
86
87 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
88 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
89 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorAutomatic;
90
91 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
92 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
93 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).Color = Word.WdColor.wdColorAutomatic;
94
95 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
96 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
97 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).Color = Word.WdColor.wdColorAutomatic;
98
99 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
100 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
101 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).Color = Word.WdColor.wdColorAutomatic;
102
103 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
104 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
105 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).Color = Word.WdColor.wdColorAutomatic;
106
107 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
108 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
109 // wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).Color = Word.WdColor.wdColorAutomatic;
110 //第一行显示
111 wordDoc.Tables.Item(1).Cell(1,2).Merge(wordDoc.Tables.Item(1).Cell(1,3));
112 wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(1,5));
113
114 //第二行显示
115 wordDoc.Tables.Item(1).Cell(2,5).Merge(wordDoc.Tables.Item(1).Cell(2,6));
116 wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(2,5));
117
118 插入数据行#region 插入数据行
119 wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "cell11";
120 //wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["cell11"].ToString();
121
122
123
124 /**/////******************
125 wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "cell13";
126 //wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["cell13"].ToString();
127
128
129
130 /**/////******************
131 wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "cell21";
132 //wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["cell21"].ToString();
133
134
135 /**/////******************
136 wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "cell23";
137 //wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["cell23"].ToString();
138
139 #endregion
140
141
142 第三行显示#region 第三行显示
143 wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
144 wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
145
146 /**/////******************
147 wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "cell31";
148
149
150
151
152
153 /**/////******************
154 wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "cell33";
155
156
157 #endregion
158
159
160 第五行显示#region 第五行显示
161 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
162 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
163 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
164 wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
165 #endregion
166
167
168 第四行显示#region 第四行显示
169
170 /**/////******************
171 wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "cell41";
172
173
174
175
176 /**/////******************
177 wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "cell43";
178
179
180
181
182 /**/////******************
183 wordDoc.Tables.Item(1).Cell(4, 5).Range.Text = "cell45";
184
185 #endregion
186
187
188 第六行显示#region 第六行显示
189 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
190 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
191 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
192 wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
193
194
195 /**/////******************
196 wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "cell51";
197
198 wordDoc.Tables.Item(1).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
199
200
201
202 /**/////******************
203 wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "cdll61";
204
205 wordDoc.Tables.Item(1).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
206 #endregion
207
208
209 第七行显示#region 第七行显示
210 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
211 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
212 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
213 wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
214
215 /**/////******************
216 wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "cell71";
217
218 wordDoc.Tables.Item(1).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
219 #endregion
220
221
222 第八行显示#region 第八行显示
223 wordDoc.Tables.Item(1).Cell(8,1).Merge(wordDoc.Tables.Item(1).Cell(8,2));
224 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
225 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
226 wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
227
228
229 #endregion
230
231
232 第九行显示#region 第九行显示
233 wordDoc.Tables.Item(1).Cell(9,1).Merge(wordDoc.Tables.Item(1).Cell(9,2));
234 wordDoc.Tables.Item(1).Cell(9,3).Merge(wordDoc.Tables.Item(1).Cell(9,4));
235
236 /**/////******************
237 wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "cell91";
238 //wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["cell91"].ToString()=="1"?"有":"无");
239
240
241
242
243 /**/////******************
244 wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "cell93";
245
246 #endregion
247
248
249 第十行显示#region 第十行显示
250 wordDoc.Tables.Item(1).Cell(10,1).Merge(wordDoc.Tables.Item(1).Cell(10,2));
251 wordDoc.Tables.Item(1).Cell(10,3).Merge(wordDoc.Tables.Item(1).Cell(10,4));
252 /**/////******************
253 wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "cell101";
254
255
256
257
258 /**/////******************
259 wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "cdll103";
260 //wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["Label"].ToString()=="1"?"有":"无");
261 #endregion
262
263
264 第十一行显示#region 第十一行显示
265 wordDoc.Tables.Item(1).Cell(11,1).Merge(wordDoc.Tables.Item(1).Cell(11,2));
266 wordDoc.Tables.Item(1).Cell(11,3).Merge(wordDoc.Tables.Item(1).Cell(11,4));
267 /**/////******************
268 wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "cell111";
269
270
271
272 /**/////******************
273 wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "cell113";
274
275 #endregion
276
277
278 第十二行显示#region 第十二行显示
279 wordDoc.Tables.Item(1).Cell(12,1).Merge(wordDoc.Tables.Item(1).Cell(12,2));
280 wordDoc.Tables.Item(1).Cell(12,3).Merge(wordDoc.Tables.Item(1).Cell(12,4));
281 /**/////******************
282 wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "cell121";
283
284
285 /**/////******************
286 wordDoc.Tables.Item(1).Cell(12, 3).Range.Text = "cell123";
287
288 #endregion
289
290
291 第十三行显示#region 第十三行显示
292 wordDoc.Tables.Item(1).Cell(13,1).Merge(wordDoc.Tables.Item(1).Cell(13,2));
293 wordDoc.Tables.Item(1).Cell(13,3).Merge(wordDoc.Tables.Item(1).Cell(13,4));
294
295 /**/////******************
296 wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "cell131";
297
298
299 /**/////******************
300 wordDoc.Tables.Item(1).Cell(13, 3).Range.Text = "cell133";
301
302 #endregion
303
304 wordDoc.Tables.Item(1).Select();
305 wordApp.Application.Selection.Cut();
306
307 //重新成声所有表
308
309
310
311
312 for(int i = 0; i<=DT.Rows.Count-1;i++)
313 {
314 wordApp.Application.Selection.Paste();
315 int k = i+1;
316 更新数据#region 更新数据
317
318
319 插入数据行#region 插入数据行
320
321 wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["1"].ToString();
322
323
324
325 /**/////******************
326
327 wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["2"].ToString();
328
329
330
331 /**/////******************
332
333 wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["3"].ToString();
334
335
336 /**/////******************
337
338 wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["4"].ToString();
339
340 #endregion
341
342
343 第三行显示#region 第三行显示
344 /**/////******************
345
346 wordDoc.Tables.Item(k).Cell(3, 2).Range.Text = DT.Rows[i]["5"].ToString();
347 /**/////******************
348
349 wordDoc.Tables.Item(k).Cell(3, 4).Range.Text = DT.Rows[i]["6"].ToString();
350
351 #endregion
352
353
354 第五行显示#region 第五行显示
355 /**/////******************
356
357 wordDoc.Tables.Item(k).Cell(5, 2).Range.Text = DT.Rows[i]["7"].ToString();
358 wordDoc.Tables.Item(k).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
359 #endregion
360
361 第四行显示#region 第四行显示
362
363 /**/////******************
364
365 wordDoc.Tables.Item(k).Cell(4, 2).Range.Text = DT.Rows[i]["8"].ToString();
366
367
368
369 /**/////******************
370
371 wordDoc.Tables.Item(k).Cell(4, 4).Range.Text = DT.Rows[i]["9"].ToString();
372
373
374
375 /**/////******************
376
377 wordDoc.Tables.Item(k).Cell(4, 6).Range.Text = DT.Rows[i]["0"].ToString();
378 #endregion
379
380
381 第六行显示#region 第六行显示
382 /**/////******************
383
384 wordDoc.Tables.Item(k).Cell(6, 2).Range.Text = DT.Rows[i]["11"].ToString();
385 wordDoc.Tables.Item(k).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
386 #endregion
387
388
389 第七行显示#region 第七行显示
390 /**/////******************
391
392 wordDoc.Tables.Item(k).Cell(7, 2).Range.Text = DT.Rows[i]["12"].ToString();
393 wordDoc.Tables.Item(k).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
394 #endregion
395
396
397 第八行显示#region 第八行显示
398 /**/////******************
399
400 string strTechlevel = DT.Rows[i]["Level"].ToString();
401 string returnTechlevel = "";
402 switch(strTechlevel)
403 {
404 case "1":
405 returnTechlevel = "Level1";
406 break;
407 case "2":
408 returnTechlevel = "Level2";
409 break;
410 case "3":
411 returnTechlevel = "Level3";
412 break;
413 case "0":
414 returnTechlevel = "Level4";
415 break;
416 default:
417 returnTechlevel = "Level5";
418 break;
419 }
420 wordDoc.Tables.Item(k).Cell(8, 2).Range.Text = returnTechlevel;
421
422 #endregion
423
424
425 第九行显示#region 第九行显示
426 /**/////******************
427
428 wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["14"].ToString()=="1"?"有":"无");
429
430
431
432
433 /**/////******************
434
435 wordDoc.Tables.Item(k).Cell(9, 4).Range.Text = (DT.Rows[i]["15"].ToString()=="1"?"是":"否");
436 #endregion
437
438
439 第十行显示#region 第十行显示
440 /**/////******************
441
442 wordDoc.Tables.Item(k).Cell(10, 2).Range.Text = (DT.Rows[i]["16"].ToString()=="1"?"有":"无");
443
444
445
446 /**/////******************
447
448 wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["17"].ToString()=="1"?"有":"无");
449 #endregion
450
451
452 第十一行显示#region 第十一行显示
453
454 /**/////******************
455
456 wordDoc.Tables.Item(k).Cell(11, 2).Range.Text = (DT.Rows[i]["18"].ToString()=="1"?"是":"否");
457
458
459 /**/////******************
460
461 wordDoc.Tables.Item(k).Cell(11, 4).Range.Text = (DT.Rows[i]["19"].ToString()=="1"?"是":"否");
462 #endregion
463
464
465 第十二行显示#region 第十二行显示
466 /**/////******************
467
468 wordDoc.Tables.Item(k).Cell(12, 2).Range.Text = (DT.Rows[i]["20"].ToString()=="1"?"是":"否");
469
470 /**/////******************
471
472 wordDoc.Tables.Item(k).Cell(12, 4).Range.Text = (DT.Rows[i]["21"].ToString()=="1"?"是":"否");
473 #endregion
474
475
476 第十三行显示#region 第十三行显示
477
478
479 wordDoc.Tables.Item(k).Cell(13, 2).Range.Text = (DT.Rows[i]["22"].ToString()=="1"?"是":"否");
480
481 /**/////******************
482
483 wordDoc.Tables.Item(k).Cell(13, 4).Range.Text = (DT.Rows[i]["23"].ToString()=="1"?"是":"否");
484 #endregion
485
486 #endregion
487
488 //插入分页
489 if(i!=DT.Rows.Count-1)
490 {
491 object mymissing = System.Reflection.Missing.Value;
492 object myunit = Word.WdUnits.wdStory;
493 wordApp.Selection.EndKey(ref myunit,ref mymissing);
494
495 object pBreak= (int)Word.WdBreakType.wdPageBreak;
496 wordApp.Selection.InsertBreak( ref pBreak );
497 }
498 }
499
500
501 wordDoc.SaveAs(ref filename, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing, ref missing);
502
503
504 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
505 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
506
507 if ( wordDoc != null )
508 {
509 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
510 wordDoc = null;
511 }
512 if ( wordApp != null )
513 {
514 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
515 wordApp = null;
516 }
517 GC.Collect();
518 //KillWordProcess();
519 string strUrl = "MakeWordFile.aspx?username="+Request.QueryString["username"].ToString();
520 utility.ShowPopMessage("文档生成完毕!",strUrl);
521 }
522 else
523 {
524 utility.ShowPopMessage("无任何数据!");
525 }
526 #endregion
527
528
529
530 }
531 catch
532 {
533 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
534 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
535 if ( wordDoc != null )
536 {
537 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
538 wordDoc = null;
539 }
540 if ( wordApp != null )
541 {
542 System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
543 wordApp = null;
544 }
545 GC.Collect();
546 utility.ShowPopMessage("文档生成失败!");
547
548 }
549 }
550
551
8 .c#读取Word
Code
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
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