一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)
在目前的软件项目中,都会较多的使用到对文档的操作,用于记录和统计相关业务信息。由于系统自身提供了对文档的相关操作,所以在一定程度上极大的简化了软件使用者的工作量。
在.NET项目中如果用户提出了相关文档操作的需求,开发者较多的会使用到微软自行提供的插件,在一定程度上简化了开发人员的工作量,但是同时也给用户带来了一些困扰,例如需要安装庞大的office,在用户体验性就会降低很多,并且在国内,很多人都还是使用wps,这就导致一部分只安装了wps的使用者很是为难,在对Excel的操作方面,有一个NPOI组件。那么可能会有人问有没有什么办法让这些困扰得到解决,答案是肯定的,那就是今天需要介绍的“DocX”组件,接下来我们就来了解一下这个组件的功能和用法。
一.DocX组件概述:
DocX是一个.NET库,允许开发人员以简单直观的方式处理Word 2007/2010/2013文件。 DocX是快速,轻量级,最好的是它不需要安装Microsoft Word或Office。DocX组件不仅可以完成对文档的一般要求,例如创建文档,创建表格和文本,并且还可以创建图形报表。DocX使创建和操作文档成为一个简单的任务。
它不使用COM库,也不需要安装Microsoft Office。在使用DocX组件时,你需要安装为了使用DocX是.NET框架4.0和Visual Studio 2010或更高版本。
DocX的主要特点:
(1).在文档中插入,删除或替换文本。所有标准文本格式都可用。 字体{系列,大小,颜色},粗体,斜体,下划线,删除线,脚本{子,超级},突出显示。
(2).段落属性显示。方向LeftToRight或RightToLeft;缩进;比对。
(3).DocX也支持:图片,超链接,表,页眉和页脚,自定义属性。
有关DocX组件的相关信息就介绍到这里,如果需要更加深入的了解相关信息,可以进入:https://docx.codeplex.com/。
二.DocX相关类和方法解析:
本文将结合DocX的源码进行解析,使用.NET Reflector对DLL文件进行反编译,以此查看源代码。将DLL文件加入.NET Reflector中,点击打开文件。
1.DocX.Create():创建文档。
public static DocX Create(Stream stream) {MemoryStream stream2 = new MemoryStream();PostCreation(ref Package.Open(stream2, FileMode.Create, FileAccess.ReadWrite));DocX cx = Load(stream2);cx.stream = stream;return cx; }
2.Paragraph.Append:向段落添加信息。
public Paragraph Append(string text) {List<XElement> content = HelperFunctions.FormatInput(text, null);base.Xml.Add(content);this.runs = base.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse<XElement>().Take<XElement>(content.Count<XElement>()).ToList<XElement>();return this; }
public Paragraph Bold() {this.ApplyTextFormattingProperty(XName.Get("b", DocX.w.NamespaceName), string.Empty, null);return this; }
3.Table.InsertTableAfterSelf:将数据插入表格。
public override Table InsertTableAfterSelf(int rowCount, int coloumnCount) {return base.InsertTableAfterSelf(rowCount, coloumnCount); }public virtual Table InsertTableAfterSelf(int rowCount, int coloumnCount) {XElement content = HelperFunctions.CreateTable(rowCount, coloumnCount);base.Xml.AddAfterSelf(content);return new Table(base.Document, base.Xml.ElementsAfterSelf().First<XElement>()); }
4.CustomProperty:自定义属性。
public class CustomProperty {// Fieldsprivate string name;private string type;private object value;// Methodspublic CustomProperty(string name, bool value);public CustomProperty(string name, DateTime value); public CustomProperty(string name, double value); public CustomProperty(string name, int value); public CustomProperty(string name, string value); private CustomProperty(string name, string type, object value); internal CustomProperty(string name, string type, string value); // Properties public string Name { get; } internal string Type { get; } public object Value { get; } }
5.BarChart:创建棒形图。
public class BarChart : Chart {// Methodspublic BarChart();protected override XElement CreateChartXml();// Propertiespublic BarDirection BarDirection { get; set; }public BarGrouping BarGrouping { get; set; }public int GapWidth { get; set; } }
public abstract class Chart {// Methodspublic Chart();public void AddLegend();public void AddLegend(ChartLegendPosition position, bool overlay);public void AddSeries(Series series);protected abstract XElement CreateChartXml(); public void RemoveLegend(); // Properties public CategoryAxis CategoryAxis { get; private set; } protected XElement ChartRootXml { get; private set; } protected XElement ChartXml { get; private set; } public DisplayBlanksAs DisplayBlanksAs { get; set; } public virtual bool IsAxisExist { get; } public ChartLegend Legend { get; private set; } public virtual short MaxSeriesCount { get; } public List<Series> Series { get; } public ValueAxis ValueAxis { get; private set; } public bool View3D { get; set; } public XDocument Xml { get; private set; } }
6.Chart的AddLegend(),AddSeries(),RemoveLegend()方法解析:
public void AddLegend(ChartLegendPosition position, bool overlay) {if (this.Legend != null){this.RemoveLegend();}this.Legend = new ChartLegend(position, overlay);this.ChartRootXml.Add(this.Legend.Xml); }
public void AddSeries(Series series) {if (this.ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)).Count<XElement>() == this.MaxSeriesCount){throw new InvalidOperationException("Maximum series for this chart is" + this.MaxSeriesCount.ToString() + "and have exceeded!");}this.ChartXml.Add(series.Xml); }
public void RemoveLegend() {this.Legend.Xml.Remove();this.Legend = null; }
以上是对DocX组件的一些方法的一些简单解析,如果需要知道更多的方法实现代码,可自行进行下载查看。
三.DocX功能实现实例:
1.创建图表:
/// <summary>/// 创建棒形图/// </summary>/// <param name="path">文档路径</param>/// <param name="dicValue">绑定数据</param>/// <param name="categoryName">类别名称</param>/// <param name="valueName">值名称</param>/// <param name="title">图标标题</param>public static bool BarChart(string path,Dictionary<string, ICollection> dicValue,string categoryName,string valueName,string title){if (string.IsNullOrEmpty(path)){throw new ArgumentNullException(path);}if (dicValue == null){throw new ArgumentNullException("dicValue");}if (string.IsNullOrEmpty(categoryName)) { throw new ArgumentNullException(categoryName); } if (string.IsNullOrEmpty(valueName)) { throw new ArgumentNullException(valueName); } if (string.IsNullOrEmpty(title)) { throw new ArgumentNullException(title); } try { using (var document = DocX.Create(path)) { //BarChart图形属性设置,BarDirection图形方向枚举,BarGrouping图形分组枚举 var c = new BarChart { BarDirection = BarDirection.Column, BarGrouping = BarGrouping.Standard, GapWidth = 400 }; //设置图表图例位置 c.AddLegend(ChartLegendPosition.Bottom, false); //写入图标数据 foreach (var chartData in dicValue) { var series = new Series(chartData.Key); series.Bind(chartData.Value, categoryName, valueName); c.AddSeries(series); } // 设置文档标题 document.InsertParagraph(title).FontSize(20); document.InsertChart(c); document.Save(); return true; } } catch (Exception ex) { throw new Exception(ex.Message); } }
2.创建一个具有超链接、图像和表的文档。
/// <summary>/// 创建一个具有超链接、图像和表的文档。/// </summary>/// <param name="path">文档保存路径</param>/// <param name="imagePath">加载的图片路径</param>/// <param name="url">url地址</param>public static void HyperlinksImagesTables(string path,string imagePath,string url){if (string.IsNullOrEmpty(path)){throw new ArgumentNullException(path);}if (string.IsNullOrEmpty(imagePath)){throw new ArgumentNullException(imagePath);}if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } try { using (var document = DocX.Create(path)) { var link = document.AddHyperlink("link", new Uri(url)); var table = document.AddTable(2, 2); table.Design = TableDesign.ColorfulGridAccent2; table.Alignment = Alignment.center; table.Rows[0].Cells[0].Paragraphs[0].Append("1"); table.Rows[0].Cells[1].Paragraphs[0].Append("2"); table.Rows[1].Cells[0].Paragraphs[0].Append("3"); table.Rows[1].Cells[1].Paragraphs[0].Append("4"); var newRow = table.InsertRow(table.Rows[1]); newRow.ReplaceText("4", "5"); var image = document.AddImage(imagePath); var picture = image.CreatePicture(); picture.Rotation = 10; picture.SetPictureShape(BasicShapes.cube); var title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS")); title.Alignment = Alignment.center; var p1 = document.InsertParagraph(); p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word."); p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append("."); p1.AppendLine(); p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?"); p1.AppendLine(); p1.AppendLine("Can you check this Table of figures for me?"); p1.AppendLine(); p1.InsertTableAfterSelf(table); var p2 = document.InsertParagraph(); p2.AppendLine("Is it correct?"); document.Save(); } } catch (Exception ex) { throw new Exception(ex.Message); } }
3.将指定内容写入文档:
/// <summary>/// 将指定内容写入文档/// </summary>/// <param name="path">加载文件路径</param>/// <param name="content">写入文件内容</param>/// <param name="savePath">保存文件路径</param>public static void ProgrammaticallyManipulateImbeddedImage(string path, string content, string savePath){if (string.IsNullOrEmpty(path)){throw new ArgumentNullException(path);}if (string.IsNullOrEmpty(content)){throw new ArgumentNullException(content);}if (string.IsNullOrEmpty(savePath)) { throw new ArgumentNullException(savePath); } try { using (var document = DocX.Load(path)) { // 确保此文档至少有一个图像。 if (document.Images.Any()) { var img = document.Images[0]; // 将内容写入图片. var b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite)); //获取此位图的图形对象,图形对象提供绘图功能。 var g = Graphics.FromImage(b); // 画字符串内容 g.DrawString ( content, new Font("Tahoma", 20), Brushes.Blue, new PointF(0, 0) ); // 使用创建\写入流将该位图保存到文档中。 b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png); } else { document.SaveAs(savePath); } } } catch (Exception ex) { throw new Exception(ex.Message); } }
四.总结:
以上是对DocX组件的API做了一个简单的解析,并且附上一些创建文档和创建图表的方法供开发者参考。
.NET组件介绍系列:
一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)http://www.cnblogs.com/pengze0902/p/6122311.html
高效而稳定的企业级.NET Office 组件Spire(.NET组件介绍之二)http://www.cnblogs.com/pengze0902/p/6125570.html
最好的.NET开源免费ZIP库DotNetZip(.NET组件介绍之三)http://www.cnblogs.com/pengze0902/p/6124659.html
免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)http://www.cnblogs.com/pengze0902/p/6134506.html
免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)http://www.cnblogs.com/pengze0902/p/6128558.html
免费高效实用的Excel操作组件NPOI(.NET组件介绍之六)http://www.cnblogs.com/pengze0902/p/6150070.html
一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)相关推荐
- qt 获取本机的wifi密码_还在记密码?这款开源免费的账号密码管理神器赶紧收了...
工作中涉及到得账号密码,你是怎么记录得?如果是文档word或者excel记录,那么回非常麻烦,每次还得打开.如果是浏览器自己记录,如果更新密码,又记不得.尴尬! 今天大卫给大家推荐一款开源免费得账号密 ...
- 五款开源免费的建站系统推荐
最近研究了下开源的建站系统,推荐5款国内的吧,都有免费版本,有需要可以去试试. ECTouch ECTouch是一款开源免费的移动商城网店系统.能够帮助企业和个人快速构建手机移动商城并减少二次开发带来 ...
- 一款开源免费且快速,高效和安全的跨平台备份程序:Restic使用教程
一款开源免费且快速,高效和安全的跨平台备份程序:Restic使用教程 Restic是使用Golang写的一款开源免费且快速,高效和安全的跨平台备份程序,可以存储在本地,云存储服务或远程文件服务器上,并 ...
- pdf加密怎么加?在线免费对PDF文档加密
pdf加密怎么加?相信许多小伙伴使用的一些pdf文件内容中都会有重要内容,总是会担心文件安全.那么今天小编就来给大家分享怎么给pdf加密~在线免费对PDF文档进行加密,不用安装任何软件程序并且每天都可 ...
- 推荐两款好用的企业文档管理软件
档案管理工作是一项专业性.政策性.机密性很强的工作,它也是信息的重要载体,信息的主要源头.无论是学校.企业或是政府都需要对档案进行管理,因此管好用好档案,对现代社会的生存与发展具有重要的现实意义. 什 ...
- 还在为不想运动而发愁吗——一款开源免费的运动记录项目
还在为不想运动而发愁吗--一款开源免费的运动记录项目 前言 现在信息日益增长.时间日益碎片化的时代,每个人都很难去坚持去一直认真做一件事情. 就拿跑步来说,许多人都是三分钟热度,根本坚持不下来.许多程 ...
- XDOC Office Server 开源了,Office文档完美转换为PDF
百度智能云 云生态狂欢季 热门云产品1折起>>> 项目地址:https://gitee.com/xdoc/xoffice XDOC是一个文档自动化平台,提供免费的Office文档 ...
- 原生仿微信社交社区即时通讯聊天双端APP源码开源带PC客户端文档说明
简介: 原生仿微信社交社区即时通讯聊天双端APP源码开源带PC客户端文档说明 5438亲测完美搭建 网盘下载地址: http://kekewangLuo.net/uiBBnJ8xQup0 图片:
- select2中文帮助文档_5款实用办公app , 石墨文档、收趣 | 发现有趣app
发现有趣app,专注分享高质量.有趣.有用的APP. 今天分享五款 :白描.石墨文档.腾讯文档.收趣.彩云小译 . 第一个:白描 白描是一款准确高效的文字识别软件. 识别速度快,准确度高,而且还能识别 ...
最新文章
- setitimer 创建两个定时器_JavaScript第二十四篇 高级定时器(下)
- 如何减少WIN7响应时间
- [原]编程融入生活---设计模式总结
- 自由主义者的周一和周五
- 在Mac OS X上安装 Ruby运行环境
- 【Node.js】编码实现目录浏览服务
- 简单实用的多线程学习实例
- 自学机器学习_我用来自学机器学习的最佳资源
- python怎么设置回文数_python如何写一个函数判断回文数?
- VC 获取当前工作目录和执行目录的一些方法
- Kubernetes 抢占调度Preempt机制源码深入剖析-Kubernetes商业环境实战
- ASP.NET中 Bin,App_Browser,App_code,App_Data,App_Theme 等文件
- layer的move要怎么用
- 什么是搜索引擎优化及其重要性
- C++进程间通信的十一种方法
- JS中的运算符号(加号)
- gc buffer busy的优化
- python3 get函数,python3请求的GET方法
- Android 8.1 9.0 10.0 在系统app安装第三方app弹出 解析安装包出现问题 的解决方案
- redis雪崩、穿透、击穿、热点分别代表什么意思?
热门文章
- 用外观判断论文好坏?这位顶会领域主席的论文被自己的AI审稿系统拒绝了
- Flink如何取代JStorm,成为字节跳动流处理唯一标准?
- snpeff注释变异(variants)
- Java EE官方文档汇总
- MySQL 5.6--------SSL连接最佳实战
- 第13章 Kotlin 集成 SpringBoot 服务端开发(1)
- 1.3.2 java程序的运行机制和jvm
- Python实现排序算法:冒泡排序,插入排序,选择排序,快速排序,希尔排序
- BT项目的运作之一项目建设方案与BT总包方的选择
- linux text mode下如何修改语言