在目前的软件项目中,都会较多的使用到对文档的操作,用于记录和统计相关业务信息。由于系统自身提供了对文档的相关操作,所以在一定程度上极大的简化了软件使用者的工作量。

在.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():创建文档。

  1. public static DocX Create(Stream stream)
  2. {
  3. MemoryStream stream2 = new MemoryStream();
  4. PostCreation(ref Package.Open(stream2, FileMode.Create, FileAccess.ReadWrite));
  5. DocX cx = Load(stream2);
  6. cx.stream = stream;
  7. return cx;
  8. }

2.Paragraph.Append:向段落添加信息。

  1. public Paragraph Append(string text)
  2. {
  3. List<XElement> content = HelperFunctions.FormatInput(text, null);
  4. base.Xml.Add(content);
  5. this.runs = base.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse<XElement>().Take<XElement>(content.Count<XElement>()).ToList<XElement>();
  6. return this;
  7. }
  1. public Paragraph Bold()
  2. {
  3. this.ApplyTextFormattingProperty(XName.Get("b", DocX.w.NamespaceName), string.Empty, null);
  4. return this;
  5. }

3.Table.InsertTableAfterSelf:将数据插入表格。

  1. public override Table InsertTableAfterSelf(int rowCount, int coloumnCount)
  2. {
  3. return base.InsertTableAfterSelf(rowCount, coloumnCount);
  4. }
  5.  
  6. public virtual Table InsertTableAfterSelf(int rowCount, int coloumnCount)
  7. {
  8. XElement content = HelperFunctions.CreateTable(rowCount, coloumnCount);
  9. base.Xml.AddAfterSelf(content);
  10. return new Table(base.Document, base.Xml.ElementsAfterSelf().First<XElement>());
  11. }

4.CustomProperty:自定义属性。

  1. public class CustomProperty
  2. {
  3. // Fields
  4. private string name;
  5. private string type;
  6. private object value;
  7.  
  8. // Methods
  9. public CustomProperty(string name, bool value);
  10. public CustomProperty(string name, DateTime value);
  11. public CustomProperty(string name, double value);
  12. public CustomProperty(string name, int value);
  13. public CustomProperty(string name, string value);
  14. private CustomProperty(string name, string type, object value);
  15. internal CustomProperty(string name, string type, string value);
  16.  
  17. // Properties
  18. public string Name { get; }
  19. internal string Type { get; }
  20. public object Value { get; }
  21. }

5.BarChart:创建棒形图。

  1. public class BarChart : Chart
  2. {
  3. // Methods
  4. public BarChart();
  5. protected override XElement CreateChartXml();
  6.  
  7. // Properties
  8. public BarDirection BarDirection { get; set; }
  9. public BarGrouping BarGrouping { get; set; }
  10. public int GapWidth { get; set; }
  11. }
  1. public abstract class Chart
  2. {
  3. // Methods
  4. public Chart();
  5. public void AddLegend();
  6. public void AddLegend(ChartLegendPosition position, bool overlay);
  7. public void AddSeries(Series series);
  8. protected abstract XElement CreateChartXml();
  9. public void RemoveLegend();
  10.  
  11. // Properties
  12. public CategoryAxis CategoryAxis { get; private set; }
  13. protected XElement ChartRootXml { get; private set; }
  14. protected XElement ChartXml { get; private set; }
  15. public DisplayBlanksAs DisplayBlanksAs { get; set; }
  16. public virtual bool IsAxisExist { get; }
  17. public ChartLegend Legend { get; private set; }
  18. public virtual short MaxSeriesCount { get; }
  19. public List<Series> Series { get; }
  20. public ValueAxis ValueAxis { get; private set; }
  21. public bool View3D { get; set; }
  22. public XDocument Xml { get; private set; }
  23. }

6.Chart的AddLegend(),AddSeries(),RemoveLegend()方法解析:

  1. public void AddLegend(ChartLegendPosition position, bool overlay)
  2. {
  3. if (this.Legend != null)
  4. {
  5. this.RemoveLegend();
  6. }
  7. this.Legend = new ChartLegend(position, overlay);
  8. this.ChartRootXml.Add(this.Legend.Xml);
  9. }
  1. public void AddSeries(Series series)
  2. {
  3. if (this.ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)).Count<XElement>() == this.MaxSeriesCount)
  4. {
  5. throw new InvalidOperationException("Maximum series for this chart is" + this.MaxSeriesCount.ToString() + "and have exceeded!");
  6. }
  7. this.ChartXml.Add(series.Xml);
  8. }
  1. public void RemoveLegend()
  2. {
  3. this.Legend.Xml.Remove();
  4. this.Legend = null;
  5. }

以上是对DocX组件的一些方法的一些简单解析,如果需要知道更多的方法实现代码,可自行进行下载查看。

三.DocX功能实现实例:

1.创建图表:

  1. /// <summary>
  2. /// 创建棒形图
  3. /// </summary>
  4. /// <param name="path">文档路径</param>
  5. /// <param name="dicValue">绑定数据</param>
  6. /// <param name="categoryName">类别名称</param>
  7. /// <param name="valueName">值名称</param>
  8. /// <param name="title">图标标题</param>
  9. public static bool BarChart(string path,Dictionary<string, ICollection> dicValue,string categoryName,string valueName,string title)
  10. {
  11. if (string.IsNullOrEmpty(path))
  12. {
  13. throw new ArgumentNullException(path);
  14. }
  15. if (dicValue == null)
  16. {
  17. throw new ArgumentNullException("dicValue");
  18. }
  19. if (string.IsNullOrEmpty(categoryName))
  20. {
  21. throw new ArgumentNullException(categoryName);
  22. }
  23. if (string.IsNullOrEmpty(valueName))
  24. {
  25. throw new ArgumentNullException(valueName);
  26. }
  27. if (string.IsNullOrEmpty(title))
  28. {
  29. throw new ArgumentNullException(title);
  30. }
  31. try
  32. {
  33. using (var document = DocX.Create(path))
  34. {
  35. //BarChart图形属性设置,BarDirection图形方向枚举,BarGrouping图形分组枚举
  36. var c = new BarChart
  37. {
  38. BarDirection = BarDirection.Column,
  39. BarGrouping = BarGrouping.Standard,
  40. GapWidth = 400
  41. };
  42. //设置图表图例位置
  43. c.AddLegend(ChartLegendPosition.Bottom, false);
  44. //写入图标数据
  45. foreach (var chartData in dicValue)
  46. {
  47. var series = new Series(chartData.Key);
  48. series.Bind(chartData.Value, categoryName, valueName);
  49. c.AddSeries(series);
  50. }
  51. // 设置文档标题
  52. document.InsertParagraph(title).FontSize(20);
  53. document.InsertChart(c);
  54. document.Save();
  55. return true;
  56. }
  57.  
  58. }
  59. catch (Exception ex)
  60. {
  61. throw new Exception(ex.Message);
  62. }
  63. }

2.创建一个具有超链接、图像和表的文档。

  1. /// <summary>
  2. /// 创建一个具有超链接、图像和表的文档。
  3. /// </summary>
  4. /// <param name="path">文档保存路径</param>
  5. /// <param name="imagePath">加载的图片路径</param>
  6. /// <param name="url">url地址</param>
  7. public static void HyperlinksImagesTables(string path,string imagePath,string url)
  8. {
  9. if (string.IsNullOrEmpty(path))
  10. {
  11. throw new ArgumentNullException(path);
  12. }
  13. if (string.IsNullOrEmpty(imagePath))
  14. {
  15. throw new ArgumentNullException(imagePath);
  16. }
  17. if (string.IsNullOrEmpty(url))
  18. {
  19. throw new ArgumentNullException(url);
  20. }
  21. try
  22. {
  23. using (var document = DocX.Create(path))
  24. {
  25. var link = document.AddHyperlink("link", new Uri(url));
  26. var table = document.AddTable(2, 2);
  27. table.Design = TableDesign.ColorfulGridAccent2;
  28. table.Alignment = Alignment.center;
  29. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  30. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  31. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  32. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  33. var newRow = table.InsertRow(table.Rows[1]);
  34. newRow.ReplaceText("4", "5");
  35. var image = document.AddImage(imagePath);
  36. var picture = image.CreatePicture();
  37. picture.Rotation = 10;
  38. picture.SetPictureShape(BasicShapes.cube);
  39. var title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  40. title.Alignment = Alignment.center;
  41. var p1 = document.InsertParagraph();
  42. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  43. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  44. p1.AppendLine();
  45. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  46. p1.AppendLine();
  47. p1.AppendLine("Can you check this Table of figures for me?");
  48. p1.AppendLine();
  49. p1.InsertTableAfterSelf(table);
  50. var p2 = document.InsertParagraph();
  51. p2.AppendLine("Is it correct?");
  52. document.Save();
  53. }
  54. }
  55. catch (Exception ex)
  56. {
  57. throw new Exception(ex.Message);
  58. }
  59.  
  60. }

3.将指定内容写入文档:

  1. /// <summary>
  2. /// 将指定内容写入文档
  3. /// </summary>
  4. /// <param name="path">加载文件路径</param>
  5. /// <param name="content">写入文件内容</param>
  6. /// <param name="savePath">保存文件路径</param>
  7. public static void ProgrammaticallyManipulateImbeddedImage(string path, string content, string savePath)
  8. {
  9. if (string.IsNullOrEmpty(path))
  10. {
  11. throw new ArgumentNullException(path);
  12. }
  13. if (string.IsNullOrEmpty(content))
  14. {
  15. throw new ArgumentNullException(content);
  16. }
  17. if (string.IsNullOrEmpty(savePath))
  18. {
  19. throw new ArgumentNullException(savePath);
  20. }
  21. try
  22. {
  23. using (var document = DocX.Load(path))
  24. {
  25. // 确保此文档至少有一个图像。
  26. if (document.Images.Any())
  27. {
  28. var img = document.Images[0];
  29. // 将内容写入图片.
  30. var b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
  31. //获取此位图的图形对象,图形对象提供绘图功能。
  32. var g = Graphics.FromImage(b);
  33. // 画字符串内容
  34. g.DrawString
  35. (
  36. content,
  37. new Font("Tahoma", 20),
  38. Brushes.Blue,
  39. new PointF(0, 0)
  40. );
  41. // 使用创建\写入流将该位图保存到文档中。
  42. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
  43. }
  44. else
  45. {
  46. document.SaveAs(savePath);
  47. }
  48. }
  49.  
  50. }
  51. catch (Exception ex)
  52. {
  53. throw new Exception(ex.Message);
  54. }
  55. }

四.总结:

以上是对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组件介绍之一)的更多相关文章

  1. Mergely – 免费的在线文档对比和合并工具

    任何类型的文件(无论是否代码),我们可能要比较不同的版本,看发生了什么变化. 有些编辑器都有这个内置功能,其中一些则没有. Mergely 是一个免费使用的 Web 应用程序,帮你你迅速作出文档的差异 ...

  2. linkedin开源的kafka-monitor安装文档

    linkedin开源的kafka-monitor安装文档 linkedin 开源的kafka-monitor的安装使用可以参考官方的readme:流程介绍的已经比较清楚,但是还是有一些地方需要修正.让 ...

  3. Uncode-Schedule首页、文档和下载 - 分布式任务调度组件 - 开源中国社区

    Uncode-Schedule首页.文档和下载 - 分布式任务调度组件 - 开源中国社区 分布式任务调度组件 Uncode-Schedule

  4. 安利一个免费下载VIP文档神器

    今天安利给大伙一个非非非常好用的可以免费下载VIP文档的下载神器------冰点文库下载器,用过的人都说好.操作简单,小巧轻便,完全免费.支持百度.豆丁.畅享.mbalib.hp009.max.boo ...

  5. jQuery 核心 - noConflict() 方法,jQuery 文档操作 - detach() 方法

    原文地址:http://www.w3school.com.cn/jquery/manipulation_detach.asp   实例 使用 noConflict() 方法为 jQuery 变量规定新 ...

  6. XML文档操作之JAXP下实现

    JAXP是java API for xml PRocessing的缩写. 其API可以在javax.xml.parsers 这个包中找到.这个包向用户提供了两个最重要的工厂类,SAXParserFac ...

  7. jQuery文档操作

    jQuery文档操作 1.jq文档结构 var $sup = $('.sup'); $sup.children(); // sup所有的子级们 $sup.parent(); // sup的父级(一个, ...

  8. 06-jQuery的文档操作

    之前js中咱们学习了js的DOM操作,也就是所谓的增删改查DOM操作.通过js的DOM的操作,大家也能发现,大量的繁琐代码实现我们想要的效果.那么jQuery的文档操作的API提供了便利的方法供我们操 ...

  9. 06-jQuery的文档操作(重点)

    之前js中咱们学习了js的DOM操作,也就是所谓的增删改查DOM操作.通过js的DOM的操作,大家也能发现,大量的繁琐代码实现我们想要的效果.那么jQuery的文档操作的API提供了便利的方法供我们操 ...

随机推荐

  1. JavaScript权威指南 - 函数

    函数本身就是一段JavaScript代码,定义一次但可能被调用任意次.如果函数挂载在一个对象上,作为对象的一个属性,通常这种函数被称作对象的方法.用于初始化一个新创建的对象的函数被称作构造函数. 相对 ...

  2. 前端框架 EasyUI (0) 重新温习(序言)

    几年前,参与过一个项目.那算是一个小型的信息管理系统,BS 结构的,前端用的是基于 jQuery 的 EasyUI 框架. 我进 Team 的时候,项目已经进入开发阶段半个多月了.听说整个项目的框架是 ...

  3. Convert BSpline Curve to Arc Spline in OpenCASCADE

    Convert BSpline Curve to Arc Spline in OpenCASCADE eryar@163.com Abstract. The paper based on OpenCA ...

  4. 计算机程序的思维逻辑 (54) - 剖析Collections - 设计模式

    上节我们提到,类Collections中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了第一类,本节我们介绍第二类. 第二类方法大概可以分为两组: 接受其他 ...

  5. 走进缓存的世界(三) - Memcache

    系列文章 走进缓存的世界(一) - 开篇 走进缓存的世界(二) - 缓存设计 走进缓存的世界(三) - Memcache 简介 Memcache是一个高性能的分布式内存对象缓存系统,用于动态Web应用 ...

  6. 设计模式C#合集--抽象工厂模式

    抽象工厂,名字就告诉你是抽象的了.上代码. public interface BMW { public void Drive(); } public class BMW730 : BMW { publ ...

  7. 【干货分享】流程DEMO-合同会审表

    流程名: 合同会审表  业务描述: 合同的审批及签订  流程相关文件: 流程包.xml 事务呈批表业务服务.xml 事务呈批表主数据.xml  流程说明: 1.此流程必须先进行事务呈批表流程的配置才可 ...

  8. 一个软件开发者的BPM之路

    我是小林,一名普通的软件工程师,从事BPM(业务流程管理)软件开发工作.我没有几十年的技术底蕴,无法像大牛们一样高谈阔论,品评BPM开发之道:也不是资深的流程管理专家,能与大家分析流程管理的时弊.我只 ...

  9. 学习C的笔记

    [unsigned] 16位系统中一个int能存储的数据的范围为-32768~32767,而unsigned能存储的数据范围则是0~65535.由于在计算机中,整数是以补码形式存放的.根据最高位的不同 ...

  10. 项目持续集成环境(jenkins + SVN + maven + tomcat)

    整体流程 每次SVN上代码有变动,触发自动构建动作,并部署到服务器的tomcat上,具体流程: 1.SVN上提交代码修改 2.maven执行Goals 3.将web工程打成war包 4.关闭服务器的t ...