欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)

程序员文章站 2022-05-26 09:52:30
在目前的软件项目中,都会较多的使用到对文档的操作,用于记录和统计相关业务信息。由于系统自身提供了对文档的相关操作,所以在一定程度上极大的简化了软件使用者的工作量。 在.n...

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

在.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组件的相关信息就介绍到这里,如果需要更加深入的了解相关信息,可以进入:。

二.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做了一个简单的解析,并且附上一些创建文档和创建图表的方法供开发者参考。希望对大家的学习有所帮助,也希望大家多多支持。