热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

利用C#技术实现Word文档的动态生成与编辑

本文通过一个简单的示例,介绍了如何使用C#语言实现Word文档的动态生成与编辑功能。文章详细阐述了在项目中引用Word动态库的方法,并通过具体代码示例展示了如何创建和操作Word表格。此内容旨在为初学者提供参考和学习资料,欢迎读者提出宝贵意见和建议。

本文以一个简单的小例子,简述利用C#语言开发word表格相关的知识,仅供学习分享使用,如有不足之处,还请指正。

在工程中引用word的动态库

在项目中,点击项目名称右键-->管理NuGet程序包,打开NuGet包管理器窗口,进行搜索下载即可,如下图所示:

C# 动态生成word文档

涉及知识点

  1. _Application: 表示word应用程序的接口,对应的实现类是Application类。
  2. _Document:表示一个word文档,通过_Application对应的文档接口进行创建。
  3. Paragraph:表示一个段落,通过_Document对象的相关方法进行创建。
  4. Table:表示一个表格,通过_Document对象的相关方法进行创建。
  5. Range:表示一个区域,可以是一个段落,也可以是一个表格,也可以是一个单元格,可以Range.select()将光标移动到当前区域。
  6. 移动焦点:wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移动焦点

生成文档效果图

C# 动态生成word文档

核心代码

  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 ETWord
 12 {
 13     public class WordHelper
 14     {
 15         public static void CreateWordFile(string filePath)
 16         {
 17             
 18             try
 19             {
 20                 CreateFile(filePath);
 21                 //
 22                 MessageFilter.Register();
 23                 object wdLine = WdUnits.wdLine;
 24                 object oMissing = Missing.Value;
 25                 object fileName = filePath;
 26                 object heading2 = WdBuiltinStyle.wdStyleHeading2;
 27                 object heading3 = WdBuiltinStyle.wdStyleHeading3;
 28                 
 29                 _Application wordApp = new Application();
 30                 wordApp.Visible = true;
 31                 _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);
 32                 System.Data.DataTable dtDepts = DatabaseHelper.getDept();
 33                 int ii = 0;
 34                 foreach (DataRow dr in dtDepts.Rows)
 35                 {
 36                     string dept = dr["dept"].ToString();
 37                     Paragraph oPara0 = wordDoc.Content.Paragraphs.Add(ref oMissing);
 38                     oPara0.Range.Text = string.Format("{0}-{1}", ii + 1, dept);
 39                     //oPara0.Range.Font.Bold = 1;
 40                     //oPara0.Format.SpaceAfter = 5;
 41                     oPara0.Range.Select();
 42                     oPara0.set_Style(ref heading2);
 43                     oPara0.Range.InsertParagraphAfter();
 44                     System.Data.DataTable dtTemplate = DatabaseHelper.getTemplateByDept(dept);
 45                     int jj = 0;
 46                     foreach (DataRow dr1 in dtTemplate.Rows)
 47                     {
 48                         string template = dr1["template"].ToString();
 49                         string user1 = dr1["user1"].ToString();
 50                         string remark = dr1["remark"].ToString();
 51                         System.Data.DataTable dtData = DatabaseHelper.getDataByDeptAndTemplate(dept, template);
 52                         int count = dtData.Rows.Count;
 53                         int row = count + 4;
 54                         int column = 5;
 55                         object ncount = 1;
 56 
 57                         wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
 58                         wordApp.Selection.TypeParagraph();
 59                         Paragraph oPara1 = wordDoc.Content.Paragraphs.Add(ref oMissing);
 60                         oPara1.Range.Select();
 61                         oPara1.Range.Text = string.Format("{0}-{1}、{2}", ii + 1, jj + 1, template);
 62                         //oPara1.Range.Font.Bold = 1;
 63                         //oPara1.Format.SpaceAfter = 5;
 64                         oPara1.set_Style(ref heading3);
 65                         oPara1.Range.InsertParagraphAfter();
 66                         wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
 67                         wordApp.Selection.TypeParagraph();
 68                         //设置表格
 69                         Table table = wordDoc.Tables.Add(wordApp.Selection.Range, row, column, ref oMissing, ref oMissing);
 70                        
 71                         table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
 72                         table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
 73                         table.Range.Font.Bold = 0;
 74                         table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthAuto;
 75                         table.Columns[1].Width = 60f;
 76                         table.Columns[2].Width = 100f;
 77                         table.Columns[3].Width = 100f;
 78                         table.Columns[4].Width = 60f;
 79                         table.Columns[5].Width = 100f;
 80                         //列的合并
 81                         Cell cell = table.Cell(1, 2);
 82                         cell.Merge(table.Cell(1, 5));
 83                         Cell cell2 = table.Cell(2, 2);
 84                         cell2.Merge(table.Cell(2, 5));
 85                         Cell cell3 = table.Cell(3, 2);
 86                         cell3.Merge(table.Cell(3, 5));
 87                         //赋值
 88                         table.Cell(1, 1).Range.Text = "流程名称:";
 89                         table.Cell(2, 1).Range.Text = "使用人:";
 90                         table.Cell(3, 1).Range.Text = "流程说明:";
 91                         table.Cell(4, 1).Range.Text = "节点";
 92                         table.Cell(4, 2).Range.Text = "节点名";
 93                         table.Cell(4, 3).Range.Text = "处理人员";
 94                         table.Cell(4, 4).Range.Text = "处理方式";
 95                         table.Cell(4, 5).Range.Text = "跳转信息";
 96                         table.Cell(1, 2).Range.Text = template;
 97                         table.Cell(2, 2).Range.Text = user1;
 98                         table.Cell(3, 2).Range.Text = remark;
 99                         int kk = 5;
100                         foreach (DataRow dr2 in dtData.Rows)
101                         {
102                             table.Cell(kk, 1).Range.Text = (kk - 4).ToString();
103                             table.Cell(kk, 2).Range.Text = dr2["NodeName"].ToString();
104                             table.Cell(kk, 3).Range.Text = dr2["DoName"].ToString();
105                             table.Cell(kk, 4).Range.Text = dr2["DoType"].ToString();
106                             table.Cell(kk, 5).Range.Text = string.Empty;
107                             kk++;
108                         }
109                         table.Cell(kk - 1, 5).Range.Select();
110 
111                         wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移动焦点
112                         wordApp.Selection.TypeParagraph();//插入段落
113 
114                         jj++;
115                     }
116                     ii++;
117                 }
118 
119                 //保存
120                 wordDoc.Save();
121                 wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
122                 wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
123                 MessageFilter.Revoke();
124 
125             }
126             catch (Exception e)
127             {
128                 Console.WriteLine(e.Message);
129                 Console.WriteLine(e.StackTrace);
130 
131             }
132         }
133 
134         private static void CreateFile(string filePath)
135         {
136             if (!File.Exists(filePath))
137             {
138                 using (FileStream fs = File.Create(filePath))
139                 {
140 
141                 }
142             }
143         }
144     }
145 }
View Code
推荐阅读
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • 本文介绍如何使用阿里云的fastjson库解析包含时间戳、IP地址和参数等信息的JSON格式文本,并进行数据处理和保存。 ... [详细]
  • ASP.NET MVC中Area机制的实现与优化
    本文探讨了在ASP.NET MVC框架中,如何通过Area机制有效地组织和管理大规模应用程序的不同功能模块。通过合理的文件夹结构和命名规则,开发人员可以更高效地管理和扩展项目。 ... [详细]
  • 本文详细介绍了中央电视台电影频道的节目预告,并通过专业工具分析了其加载方式,确保用户能够获取最准确的电视节目信息。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Windows服务与数据库交互问题解析
    本文探讨了在Windows 10(64位)环境下开发的Windows服务,旨在定期向本地MS SQL Server (v.11)插入记录。尽管服务已成功安装并运行,但记录并未正确插入。我们将详细分析可能的原因及解决方案。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 主要用了2个类来实现的,话不多说,直接看运行结果,然后在奉上源代码1.Index.javaimportjava.awt.Color;im ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • 本文探讨了 Objective-C 中的一些重要语法特性,包括 goto 语句、块(block)的使用、访问修饰符以及属性管理等。通过实例代码和详细解释,帮助开发者更好地理解和应用这些特性。 ... [详细]
  • 本文详细介绍了Java中org.w3c.dom.Text类的splitText()方法,通过多个代码示例展示了其实际应用。该方法用于将文本节点在指定位置拆分为两个节点,并保持在文档树中。 ... [详细]
  • 本文详细介绍了 Apache Jena 库中的 Txn.executeWrite 方法,通过多个实际代码示例展示了其在不同场景下的应用,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 根据最新发布的《互联网人才趋势报告》,尽管大量IT从业者已转向Python开发,但随着人工智能和大数据领域的迅猛发展,仍存在巨大的人才缺口。本文将详细介绍如何使用Python编写一个简单的爬虫程序,并提供完整的代码示例。 ... [详细]
author-avatar
mobiledu2502874377
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有