前言

本篇主要记录: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. [译]Vulkan教程(05)Instance

    [译]Vulkan教程(05)Instance Creating an instance 创建一个instance The very first thing you need to do is ini ...

  2. go语言的json

    简介 json 中提供的处理 json 的标准包是 encoding/json,主要使用的是以下两个方法: // 序列化 func Marshal(v interface{}) ([]byte, er ...

  3. 【构建之法教学项目】一个简单的基于C#的电子商务系统演练场景的代码示例

    电子商务平台,是一个历史悠久而又充满挑战的行业,他和社交一起成为中国互联网市场的两极.电子商务系统是一个非常复杂的系统,他实现了人与物.人与人的链接,同时也需要大量的技术来支撑,实现系统的高可用.这些 ...

  4. 我的计划任务 --- 实现市电停电安全关闭群辉,Windows, Linux等设备

    有一次突然停电,我的群辉DS218+ 的一块硬盘出现故障了,让我担心我的数据安全,其实我是有UPS, 不是在线式的,然后就想如何实现停电自动关机呢? 经过半天的了解,其实群辉支持telnet协议,于是 ...

  5. log4j配置项

    log4j 配置文件log4j.rootLogger=INFO,console,dailyFile# 控制台配置项log4j.appender.console=org.apache.log4j.Con ...

  6. 简单快速上手Jackson使用

    1简介 Jackson具有比较高的序列化和反序列化效率,据测试,无论是哪种形式的转换,Jackson > Gson > Json-lib,而且Jackson的处理能力甚至高出Json-li ...

  7. C#(1)运用C#实现一键从Word文档转换TXT文本的功能

    有想直接从Word转TXT文本的可以看看,懒得复制粘贴的也可以使用下,方便而快捷!! 首先打开vs2012创建一个简单的form窗体: 里面主要的就是一个存放Word文档的button和一个执行的bu ...

  8. swift字符串截取实例

    截取字符串 let deviceStr = deviceInfoLabel.attributedText?.string var device  = "" if let len : ...

  9. gcc 4.9 编译安装 in Ubuntu 18.04(主要用于在无root权限下,进行更新系统 gcc 版本)

    gcc 4.9 编译安装教程,因为项目编译过程中,需要采用特定的gcc版本来进行编译,所以进行简要记录,进行备忘: 下载:curl -O -L https://mirrors.tuna.tsinghu ...

  10. LRU的实现(使用list)

    首先是LRU的定义,LRU表示最近最少使用,如果数据最近被访问过,那么将来被访问的几率也更高. 所以逻辑应该是每次都要将新被访问的页放到列表头部,如果超过了list长度限制,就将列表尾部的元素踢出去. ...