网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

.NET中开源文档操作组件DocX怎么用-创新互联

这篇文章主要介绍.NET中开源文档操作组件DocX怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比丰林网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式丰林网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖丰林地区。费用合理售后完善,十年实体公司更值得信赖。

一.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).段落属性显示。方向LeftToRightRightToLeft;缩进;比对。

     (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 content = HelperFunctions.FormatInput(text, null);
 base.Xml.Add(content);
 this.runs = base.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse().Take(content.Count()).ToList();
 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());
}

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 { 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() == 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.创建图表:

  /// 
  /// 创建棒形图
  /// 
  /// 文档路径
  /// 绑定数据
  /// 类别名称
  /// 值名称
  /// 图标标题
  public static bool BarChart(string path,Dictionary 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.创建一个具有超链接、图像和表的文档。

  /// 
  /// 创建一个具有超链接、图像和表的文档。
  /// 
  /// 文档保存路径
  /// 加载的图片路径
  /// url地址
  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.将指定内容写入文档:

  /// 
  /// 将指定内容写入文档
  /// 
  /// 加载文件路径
  /// 写入文件内容
  /// 保存文件路径
  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);
   }
  }

以上是“.NET中开源文档操作组件DocX怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


分享题目:.NET中开源文档操作组件DocX怎么用-创新互联
路径分享:http://bjjierui.cn/article/pessc.html

其他资讯