前言

本篇主要记录: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. Office批量打印助手(Excel 批量打印、Word 批量打印)

    最新版本:1.0.6664.34636(更新日期:2018年3月31日) 下载地址:点击下载  程序简介: 本程序能批量打印 Word 文件.Excel 工作簿. 使用程序前请先安装 .NET Fra ...

  2. RabbitMQ几个常用面试题

    以下观点,仅为个人理解的总结,如有错漏,欢迎指正! -------------------------------------------------------------------------- ...

  3. angularjs路由监听,uirouter感知路由变化,解决uirouter路由监听不生效的问题

     壹 ❀ 引 angularjs除了惊为天人的双向数据绑定外,路由也是出彩的一笔,通过路由配置,我们能在不发起页面跳转的情况下,对当前页内容进行整体更新,angularjs提供了ngRoute模块用于 ...

  4. .net实现一个简单的通用查询数据、导出Excel的网页

    背景:临时提供一个简单的网页,供其他人浏览数据库(Oracel.MSSQL)的某些数据,并导出Excel.支持在配置文件中随时添加或修改sql. 实现:把sql语句等信息保存一个xml文件中,前端页面 ...

  5. python中函数

    函数特点:一次定义,多次调用 函数阶段:1.定义阶段 2.调用阶段定义阶段的参数叫形参 调用阶段的参数叫实参 例: def test(name,age): print('my name is %s,m ...

  6. EChart绘制风速风向曲线分析图

    1.获取ECharts 在 ECharts 的 GitHub 上下载最新的 release 版本,解压出来的文件夹里的 dist 目录里可以找到最新版本的 echarts 库. 2.引入ECharts ...

  7. Python比较配置文件

    工作中最常见的配置文件有四种:普通key=value的配置文件.Json格式的配置文件.HTML格式的配置文件以及YAML配置文件. 这其中以第一种居多,后三种在成熟的开源产品中较为常见,本文只针对第 ...

  8. liunx用户环境初始化脚本

          liunx用户环境初始化脚本 编写生成脚本基本格式,包括作者,联系方式,版本,时间,描述等 [root@magedu ~]# vim .vimrc set ignorecase set c ...

  9. React中条件渲染

    17==> 条件渲染 state初始化一般写在构造器当中 CharShop.js如下 import React, { Component } from "react"; ex ...

  10. Java程序猿想要月薪2万+必须必备哪些技术?

    现在程序员是比较紧俏的一个岗位,其实可以写代码的人许多,但是为什么程序员还那么缺呢? 除了需求大以外,还有一个原因就是,实在合格的程序员确实比较少. 想要成为一个合格的程序员,咱们需求满意以下几点要求 ...