前言
本篇主要记录:VS2019 WinFrm桌面应用程序实现对Word文档的简单操作。
准备工作
搭建WinFrm前台界面
添加必要的控件,如下图
NuGet包管理器
安装Microsoft.Office.Interop.Word包。
核心代码
WordHleper.cs
1 using Microsoft.Office.Interop.Word; 2 using System; 3 using System.Collections.Generic; 4 using System.Data; 5 using System.IO; 6 using System.Linq; 7 using System.Reflection; 8 using System.Text; 9 using System.Threading.Tasks; 10 11 namespace CreateWord 12 { 13 class WordHelper 14 { 15 public static void CreateWordFile(string filePath) 16 { 17 try 18 { 19 CreateFile(filePath); 20 // 21 MessageFilter.Register(); 22 object wdLine = WdUnits.wdLine; 23 object oMissing = Missing.Value; 24 object fileName = filePath; 25 object heading2 = WdBuiltinStyle.wdStyleHeading2; 26 object heading3 = WdBuiltinStyle.wdStyleHeading3; 27 28 _Application wordApp = new Application(); 29 wordApp.Visible = true; 30 _Document wordDoc = wordApp.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 31 System.Data.DataTable dtDepts = DatabaseHelper.getDept(); 32 int ii = 0; 33 foreach (DataRow dr in dtDepts.Rows) 34 { 35 string dept = dr["dept"].ToString(); 36 Paragraph oPara0 = wordDoc.Content.Paragraphs.Add(ref oMissing); 37 oPara0.Range.Text = string.Format("{0}-{1}", ii + 1, dept); 38 //oPara0.Range.Font.Bold = 1; 39 //oPara0.Format.SpaceAfter = 5; 40 oPara0.Range.Select(); 41 oPara0.set_Style(ref heading2); 42 oPara0.Range.InsertParagraphAfter(); 43 System.Data.DataTable dtTemplate = DatabaseHelper.getTemplateByDept(dept); 44 int jj = 0; 45 foreach (DataRow dr1 in dtTemplate.Rows) 46 { 47 string template = dr1["template"].ToString(); 48 string user1 = dr1["user1"].ToString(); 49 string remark = dr1["remark"].ToString(); 50 System.Data.DataTable dtData = DatabaseHelper.getDataByDeptAndTemplate(dept, template); 51 int count = dtData.Rows.Count; 52 int row = count + 4; 53 int column = 5; 54 object ncount = 1; 55 56 wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing); 57 wordApp.Selection.TypeParagraph(); 58 Paragraph oPara1 = wordDoc.Content.Paragraphs.Add(ref oMissing); 59 oPara1.Range.Select(); 60 oPara1.Range.Text = string.Format("{0}-{1}、{2}", ii + 1, jj + 1, template); 61 //oPara1.Range.Font.Bold = 1; 62 //oPara1.Format.SpaceAfter = 5; 63 oPara1.set_Style(ref heading3); 64 oPara1.Range.InsertParagraphAfter(); 65 wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing); 66 wordApp.Selection.TypeParagraph(); 67 //设置表格 68 Table table = wordDoc.Tables.Add(wordApp.Selection.Range, row, column, ref oMissing, ref oMissing); 69 70 table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; 71 table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; 72 table.Range.Font.Bold = 0; 73 table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthAuto; 74 table.Columns[1].Width = 60f; 75 table.Columns[2].Width = 100f; 76 table.Columns[3].Width = 100f; 77 table.Columns[4].Width = 60f; 78 table.Columns[5].Width = 100f; 79 //列的合并 80 Cell cell = table.Cell(1, 2); 81 cell.Merge(table.Cell(1, 5)); 82 Cell cell2 = table.Cell(2, 2); 83 cell2.Merge(table.Cell(2, 5)); 84 Cell cell3 = table.Cell(3, 2); 85 cell3.Merge(table.Cell(3, 5)); 86 //赋值 87 table.Cell(1, 1).Range.Text = "流程名称:"; 88 table.Cell(2, 1).Range.Text = "使用人:"; 89 table.Cell(3, 1).Range.Text = "流程说明:"; 90 table.Cell(4, 1).Range.Text = "节点"; 91 table.Cell(4, 2).Range.Text = "节点名"; 92 table.Cell(4, 3).Range.Text = "处理人员"; 93 table.Cell(4, 4).Range.Text = "处理方式"; 94 table.Cell(4, 5).Range.Text = "跳转信息"; 95 table.Cell(1, 2).Range.Text = template; 96 table.Cell(2, 2).Range.Text = user1; 97 table.Cell(3, 2).Range.Text = remark; 98 int kk = 5; 99 foreach (DataRow dr2 in dtData.Rows) 100 { 101 table.Cell(kk, 1).Range.Text = (kk - 4).ToString(); 102 table.Cell(kk, 2).Range.Text = dr2["NodeName"].ToString(); 103 table.Cell(kk, 3).Range.Text = dr2["DoName"].ToString(); 104 table.Cell(kk, 4).Range.Text = dr2["DoType"].ToString(); 105 table.Cell(kk, 5).Range.Text = string.Empty; 106 kk++; 107 } 108 table.Cell(kk - 1, 5).Range.Select(); 109 110 wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移动焦点 111 wordApp.Selection.TypeParagraph();//插入段落 112 113 jj++; 114 } 115 ii++; 116 } 117 118 //保存 119 wordDoc.Save(); 120 wordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 121 wordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 122 MessageFilter.Revoke(); 123 124 } 125 catch (Exception e) 126 { 127 Console.WriteLine(e.Message); 128 Console.WriteLine(e.StackTrace); 129 130 } 131 } 132 133 ///134 /// 创建文件 135 /// 136 /// 137 private static void CreateFile(string filePath) 138 { 139 if (!File.Exists(filePath)) 140 { 141 using (FileStream fs = File.Create(filePath)) 142 { 143 144 } 145 } 146 } 147 } 148 }
DatabaseHelper.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace CreateWord 9 { 10 public class DatabaseHelper 11 { 12 ///13 /// 获取部门 14 /// 15 /// 16 public static DataTable getDept() 17 { 18 DataTable dt = new DataTable(); 19 dt.Columns.Add("dept"); 20 for (int i = 0; i < 5; i++) 21 { 22 DataRow dr = dt.NewRow(); 23 dr["dept"] = string.Format("部门_{0}_T", i + 1); 24 dt.Rows.Add(dr); 25 } 26 return dt; 27 } 28 29 /// 30 /// 获取模板 31 /// 32 /// 33 /// 34 public static DataTable getTemplateByDept(string dept) 35 { 36 DataTable dt = new DataTable(); 37 dt.Columns.Add("template"); 38 dt.Columns.Add("user1"); 39 dt.Columns.Add("remark"); 40 for (int i = 0; i < 5; i++) 41 { 42 DataRow dr = dt.NewRow(); 43 dr["template"] = string.Format("小组_{0}_A_{1}", i + 1, dept); 44 dr["user1"] = string.Format("B_{0}_B_{1}", i + 1, dept); 45 dr["remark"] = string.Format("C_{0}_C_{1}", i + 1, dept); 46 dt.Rows.Add(dr); 47 } 48 return dt; 49 } 50 51 /// 52 /// 获取数据 53 /// 54 /// 55 /// 56 /// 57 public static DataTable getDataByDeptAndTemplate(string dept, string template) 58 { 59 DataTable dt = new DataTable(); 60 dt.Columns.Add("NodeName"); 61 dt.Columns.Add("DoName"); 62 dt.Columns.Add("DoType"); 63 for (int i = 0; i < 5; i++) 64 { 65 DataRow dr = dt.NewRow(); 66 dr["NodeName"] = string.Format("AA_{0}_{1}", i, template); 67 dr["DoName"] = string.Format("BB_{0}", i); 68 dr["DoType"] = string.Format("CC_{0}", i); 69 dt.Rows.Add(dr); 70 } 71 return dt; 72 } 73 } 74 }
Messagefilter.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace CreateWord 9 { 10 public class MessageFilter : IOleMessageFilter 11 { 12 // 13 // Class containing the IOleMessageFilter 14 // thread error-handling functions. 15 16 // Start the filter. 17 public static void Register() 18 { 19 IOleMessageFilter newFilter = new MessageFilter(); 20 IOleMessageFilter oldFilter = null; 21 CoRegisterMessageFilter(newFilter, out oldFilter); 22 } 23 24 // Done with the filter, close it. 25 public static void Revoke() 26 { 27 IOleMessageFilter oldFilter = null; 28 CoRegisterMessageFilter(null, out oldFilter); 29 } 30 31 // 32 // IOleMessageFilter functions. 33 // Handle incoming thread requests. 34 int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo) 35 { 36 //Return the flag SERVERCALL_ISHANDLED. 37 return 0; 38 } 39 40 // Thread call was rejected, so try again. 41 int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType) 42 { 43 if (dwRejectType == 2) 44 // flag = SERVERCALL_RETRYLATER. 45 { 46 // Retry the thread call immediately if return >=0 & 47 // <100. 48 return 99; 49 } 50 // Too busy; cancel call. 51 return -1; 52 } 53 54 int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee, int dwTickCount, int dwPendingType) 55 { 56 //Return the flag PENDINGMSG_WAITDEFPROCESS. 57 return 2; 58 } 59 60 // Implement the IOleMessageFilter interface. 61 [DllImport("Ole32.dll")] 62 private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter); 63 } 64 65 [ComImport(), Guid("00000016-0000-0000-C000-000000000046"), 66 InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] 67 interface IOleMessageFilter 68 { 69 [PreserveSig] 70 int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo); 71 72 [PreserveSig] 73 int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType); 74 75 [PreserveSig] 76 int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType); 77 } 78 }
运行效果
参考资料:
https://wenku.baidu.com/view/95ed9a410640be1e650e52ea551810a6f424c861
https://www.cnblogs.com/hsiang/p/9919605.html
作者:Jeremy.Wu
出处:https://www.cnblogs.com/jeremywucnblog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。