前言

本篇主要记录:VS2019 WinFrm桌面应用程序实现对Word文档的简单操作。

准备工作

搭建WinFrm前台界面

添加必要的控件,如下图

NuGet包管理器

安装Microsoft.Office.Interop.Word包。

核心代码

WordHleper.cs

 using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace CreateWord
{
class WordHelper
{
public static void CreateWordFile(string filePath)
{
try
{
CreateFile(filePath);
//
MessageFilter.Register();
object wdLine = WdUnits.wdLine;
object oMissing = Missing.Value;
object fileName = filePath;
object heading2 = WdBuiltinStyle.wdStyleHeading2;
object heading3 = WdBuiltinStyle.wdStyleHeading3; _Application wordApp = new Application();
wordApp.Visible = true;
_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);
System.Data.DataTable dtDepts = DatabaseHelper.getDept();
int ii = ;
foreach (DataRow dr in dtDepts.Rows)
{
string dept = dr["dept"].ToString();
Paragraph oPara0 = wordDoc.Content.Paragraphs.Add(ref oMissing);
oPara0.Range.Text = string.Format("{0}-{1}", ii + , dept);
//oPara0.Range.Font.Bold = 1;
//oPara0.Format.SpaceAfter = 5;
oPara0.Range.Select();
oPara0.set_Style(ref heading2);
oPara0.Range.InsertParagraphAfter();
System.Data.DataTable dtTemplate = DatabaseHelper.getTemplateByDept(dept);
int jj = ;
foreach (DataRow dr1 in dtTemplate.Rows)
{
string template = dr1["template"].ToString();
string user1 = dr1["user1"].ToString();
string remark = dr1["remark"].ToString();
System.Data.DataTable dtData = DatabaseHelper.getDataByDeptAndTemplate(dept, template);
int count = dtData.Rows.Count;
int row = count + ;
int column = ;
object ncount = ; wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
wordApp.Selection.TypeParagraph();
Paragraph oPara1 = wordDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Select();
oPara1.Range.Text = string.Format("{0}-{1}、{2}", ii + , jj + , template);
//oPara1.Range.Font.Bold = 1;
//oPara1.Format.SpaceAfter = 5;
oPara1.set_Style(ref heading3);
oPara1.Range.InsertParagraphAfter();
wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
wordApp.Selection.TypeParagraph();
//设置表格
Table table = wordDoc.Tables.Add(wordApp.Selection.Range, row, column, ref oMissing, ref oMissing); table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
table.Range.Font.Bold = ;
table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthAuto;
table.Columns[].Width = 60f;
table.Columns[].Width = 100f;
table.Columns[].Width = 100f;
table.Columns[].Width = 60f;
table.Columns[].Width = 100f;
//列的合并
Cell cell = table.Cell(, );
cell.Merge(table.Cell(, ));
Cell cell2 = table.Cell(, );
cell2.Merge(table.Cell(, ));
Cell cell3 = table.Cell(, );
cell3.Merge(table.Cell(, ));
//赋值
table.Cell(, ).Range.Text = "流程名称:";
table.Cell(, ).Range.Text = "使用人:";
table.Cell(, ).Range.Text = "流程说明:";
table.Cell(, ).Range.Text = "节点";
table.Cell(, ).Range.Text = "节点名";
table.Cell(, ).Range.Text = "处理人员";
table.Cell(, ).Range.Text = "处理方式";
table.Cell(, ).Range.Text = "跳转信息";
table.Cell(, ).Range.Text = template;
table.Cell(, ).Range.Text = user1;
table.Cell(, ).Range.Text = remark;
int kk = ;
foreach (DataRow dr2 in dtData.Rows)
{
table.Cell(kk, ).Range.Text = (kk - ).ToString();
table.Cell(kk, ).Range.Text = dr2["NodeName"].ToString();
table.Cell(kk, ).Range.Text = dr2["DoName"].ToString();
table.Cell(kk, ).Range.Text = dr2["DoType"].ToString();
table.Cell(kk, ).Range.Text = string.Empty;
kk++;
}
table.Cell(kk - , ).Range.Select(); wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移动焦点
wordApp.Selection.TypeParagraph();//插入段落 jj++;
}
ii++;
} //保存
wordDoc.Save();
wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
MessageFilter.Revoke(); }
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace); }
} /// <summary>
/// 创建文件
/// </summary>
/// <param name="filePath"></param>
private static void CreateFile(string filePath)
{
if (!File.Exists(filePath))
{
using (FileStream fs = File.Create(filePath))
{ }
}
}
}
}

DatabaseHelper.cs

 using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CreateWord
{
public class DatabaseHelper
{
/// <summary>
/// 获取部门
/// </summary>
/// <returns></returns>
public static DataTable getDept()
{
DataTable dt = new DataTable();
dt.Columns.Add("dept");
for (int i = ; i < ; i++)
{
DataRow dr = dt.NewRow();
dr["dept"] = string.Format("部门_{0}_T", i + );
dt.Rows.Add(dr);
}
return dt;
} /// <summary>
/// 获取模板
/// </summary>
/// <param name="dept"></param>
/// <returns></returns>
public static DataTable getTemplateByDept(string dept)
{
DataTable dt = new DataTable();
dt.Columns.Add("template");
dt.Columns.Add("user1");
dt.Columns.Add("remark");
for (int i = ; i < ; i++)
{
DataRow dr = dt.NewRow();
dr["template"] = string.Format("小组_{0}_A_{1}", i + , dept);
dr["user1"] = string.Format("B_{0}_B_{1}", i + , dept);
dr["remark"] = string.Format("C_{0}_C_{1}", i + , dept);
dt.Rows.Add(dr);
}
return dt;
} /// <summary>
/// 获取数据
/// </summary>
/// <param name="dept"></param>
/// <param name="template"></param>
/// <returns></returns>
public static DataTable getDataByDeptAndTemplate(string dept, string template)
{
DataTable dt = new DataTable();
dt.Columns.Add("NodeName");
dt.Columns.Add("DoName");
dt.Columns.Add("DoType");
for (int i = ; i < ; i++)
{
DataRow dr = dt.NewRow();
dr["NodeName"] = string.Format("AA_{0}_{1}", i, template);
dr["DoName"] = string.Format("BB_{0}", i);
dr["DoType"] = string.Format("CC_{0}", i);
dt.Rows.Add(dr);
}
return dt;
}
}
}

Messagefilter.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace CreateWord
{
public class MessageFilter : IOleMessageFilter
{
//
// Class containing the IOleMessageFilter
// thread error-handling functions. // Start the filter.
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
} // Done with the filter, close it.
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
} //
// IOleMessageFilter functions.
// Handle incoming thread requests.
int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
{
//Return the flag SERVERCALL_ISHANDLED.
return ;
} // Thread call was rejected, so try again.
int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == )
// flag = SERVERCALL_RETRYLATER.
{
// Retry the thread call immediately if return >=0 &
// <100.
return ;
}
// Too busy; cancel call.
return -;
} int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
{
//Return the flag PENDINGMSG_WAITDEFPROCESS.
return ;
} // Implement the IOleMessageFilter interface.
[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
} [ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo); [PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType); [PreserveSig]
int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}
}

运行效果

参考资料:

https://wenku.baidu.com/view/95ed9a410640be1e650e52ea551810a6f424c861

https://www.cnblogs.com/hsiang/p/9919605.html

作者:Jeremy.Wu
  出处:https://www.cnblogs.com/jeremywucnblog/

  本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

C# - 操作Word文档小实验的更多相关文章

  1. iText操作word文档总结

    操作word文档的工具有很多,除了iText之外还有POI,但是POI擅长的功能是操作excel,虽然也可以操作word,但是能力有限,而且还有很多的bug,技术并不成熟,下面就重点介绍一种操作wor ...

  2. C#操作Word文档(加密、解密、对应书签插入分页符)

    原文:C#操作Word文档(加密.解密.对应书签插入分页符) 最近做一个项目,客户要求对已经生成好的RTF文件中的内容进行分页显示,由于之前对这方面没有什么了解,后来在网上也找了相关的资料,并结合自己 ...

  3. 利用Python操作Word文档【图片】

    利用Python操作Word文档

  4. Java文件操作系列[3]——使用jacob操作word文档

    Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...

  5. VC操作WORD文档总结

    一.写在开头 最近研究word文档的解析技术,我本身是VC的忠实用户,看到C#里面操作WORD这么舒服,同时也看到单位有一些需求,就想尝试一下,结果没想到里面的技术点真不少,同时网络上的共享资料很多, ...

  6. QTP操作word文档

    QTP可以对word文档进行操作,这里最主要展示的是向word文档写入内容,并保存的功能. Option explicit Dim wordApp Set wordApp = createobject ...

  7. c#中操作word文档-四、对象模型

    转自:http://blog.csdn.net/ruby97/article/details/7406806 Word对象模型  (.Net Perspective) 本文主要针对在Visual St ...

  8. python 操作word文档

    因为工作需要操作一些word文档,记录一下学习思路 #-*- encoding: utf8 -*- import win32com from win32com.client import Dispat ...

  9. 2.QT中操作word文档

     Qt/Windows桌面版提供了ActiveQt框架,用以为Qt和ActiveX提供完美结合.ActiveQt由两个模块组成: A   QAxContainer模块允许我们使用COM对象并且可以 ...

随机推荐

  1. java高并发系列 - 第20天:JUC中的Executor框架详解2之ExecutorCompletionService

    这是java高并发系列第20篇文章. 本文内容 ExecutorCompletionService出现的背景 介绍CompletionService接口及常用的方法 介绍ExecutorComplet ...

  2. goweb-mysql连接

    操作 数据库 Go 语言中的 database/sql 包定义了对数据库的一系列操作.database/sql/driver 包定义了应被数据库驱动实现的接口,这些接口会被 sql 包使用.但是 Go ...

  3. PlayJava Day012

    今日所学: /* 2019.08.19开始学习,此为补档. */ JPanel和JFrame 1.JFrame是最底层,JPanel是置于其面上,同一个界面只有一个JFrame,一个JFrame可以放 ...

  4. Oracle数据库之第四篇

    /* 授权命令 grant 权限 to 用户 授权可以授予多个权限 grant connect,resource to baidu 收回权限 revoke 权限 from 用户 revoke dba ...

  5. The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

    介绍 再使用spring操作mysql数据库报错 @Test public void test() { try { //创建连接池,先使用spring框架内置的连接池 DriverManagerDat ...

  6. .Net Core MVC理解新管道处理模型、中间件

    .Net Core中间件官网:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore ...

  7. JavaScript 使用new关键字调用函数

    使用new关键字调用函数 test.js 代码如下 function Person(name, age, obj) { var o = new Object(); o.name = name; o.a ...

  8. ArcGIS api for JavaScript 3.27 在线浏览的一些小部件

    var navOption; var navToolbar;// 当前选择的操作 require( [ "esri/toolbars/navigation", "esri ...

  9. Thymeleaf常用语法:HTML属性设置

    使用Thymeleaf的属性来设置HTML属性.(1)使用th:attr属性可以修改原来HTML节点的属性:(2)th:attr属性可以同时设置多个属性:(3)每一个HTML属性都有对应的Thymel ...

  10. 执行 Run manage.py Task 报 AttributeError: 'Command' object has no attribute 'usage'?

    这个问题,是python与Pycharm不兼容导致,解决办法将Pycharm升级最新版本