全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

详解一款开源免费的.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
{
  // Fields
  private string name;
  private string type;
  private object value;

  // Methods
  public 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
{
  // Methods
  public BarChart();
  protected override XElement CreateChartXml();

  // Properties
  public BarDirection BarDirection { get; set; }
  public BarGrouping BarGrouping { get; set; }
  public int GapWidth { get; set; }
}
public abstract class Chart
{
  // Methods
  public 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做了一个简单的解析,并且附上一些创建文档和创建图表的方法供开发者参考。希望对大家的学习有所帮助,也希望大家多多支持。


# asp.net  # 操作word文档  # .net  # .NET文档操作  # .NET 开源配置组件 AgileConfig的使用简介  # ASP.NET开源导入导出库Magicodes.IE完成Csv导入导出的方法  # 详解开源免费且稳定实用的.NET PDF打印组件itextSharp(.NET组件介绍之八)  # 详解免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四  # 详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)  # 详解最好的.NET开源免费ZIP库DotNetZip(.NET组件介绍之三)  # 详解免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)  # .NET中开源文档操作组件DocX的介绍与使用  # 基于.NET平台常用的框架和开源程序整理  # .NET 开源项目Polly的简单介绍  # 文档  # 超链接  # 相关信息  # 较多  # 自定义  # 在一  # 开发人员  # 创建一个  # 有一个  # 的是  # 是一个  # 加载  # 就会  # 不需要安装  # 还可以  # 很多人  # 下划线  # 提出了  # 这就  # 微软 


相关文章: ,怎么用自己头像做动态表情包?  宝塔建站无法访问?如何排查配置与端口问题?  javascript基本数据类型及类型检测常用方法小结  C++如何将C风格字符串(char*)转换为std::string?(代码示例)  实惠建站价格推荐:2025年高性价比自助建站套餐解析  如何选择高效响应式自助建站源码系统?  建站之星伪静态规则如何正确配置?  武清网站制作公司,天津武清个人营业执照注销查询系统网站?  如何在服务器上三步完成建站并提升流量?  如何快速搭建安全的FTP站点?  如何在万网开始建站?分步指南解析  如何在云虚拟主机上快速搭建个人网站?  如何在橙子建站中快速调整背景颜色?  建站之星五站合一营销型网站搭建攻略,流量入口全覆盖优化指南  h5网站制作工具有哪些,h5页面制作工具有哪些?  文字头像制作网站推荐软件,醒图能自动配文字吗?  高防服务器如何保障网站安全无虞?  教学网站制作软件,学习*后期制作的网站有哪些?  如何在VPS电脑上快速搭建网站?  香港服务器租用每月最低只需15元?  如何生成腾讯云建站专用兑换码?  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  湖北网站制作公司有哪些,湖北清能集团官网?  如何零基础在云服务器搭建WordPress站点?  网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?  建站之星如何助力网站排名飙升?揭秘高效技巧  青浦网站制作公司有哪些,苹果官网发货地是哪里?  高防网站服务器:DDoS防御与BGP线路的AI智能防护方案  已有域名如何免费搭建网站?  网站专业制作公司,网站编辑是做什么的?好做吗?工作前景如何?  小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?  网站制作中优化长尾关键字挖掘的技巧,建一个视频网站需要多少钱?  武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?  定制建站是什么?如何实现个性化需求?  广州顶尖建站服务:企业官网建设与SEO优化一体化方案  建站主机选购指南与交易推荐:核心配置解析  教程网站设计制作软件,怎么创建自己的一个网站?  太原网站制作公司有哪些,网约车营运证查询官网?  c++如何打印函数堆栈信息_c++ backtrace函数与符号名解析【方法】  如何制作算命网站,怎么注册算命网站?  专业制作网站的公司哪家好,建立一个公司网站的费用.有哪些部分,分别要多少钱?  小型网站制作HTML,*游戏网站怎么搭建?  郑州企业网站制作公司,郑州招聘网站有哪些?  制作表格网站有哪些,线上表格怎么弄?  c++ stringstream用法详解_c++字符串与数字转换利器  如何快速搭建二级域名独立网站?  图册素材网站设计制作软件,图册的导出方式有几种?  网站企业制作流程,用什么语言做企业网站比较好?  如何用y主机助手快速搭建网站?  北京企业网站设计制作公司,北京铁路集团官方网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。