最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.NET中開源文檔操作組件DocX的介紹與使用

 更新時間:2016年12月02日 11:02:45   作者:彭澤0902  
在大家日常開發(fā)中讀寫Offic格式的文檔,大家多少都有用到,可能方法也很多,組件有很多。這里不去討論其他方法的優(yōu)劣,只是向大家介紹一款開源的讀寫word文檔的組件。讀寫Excel有NPOI,讀寫Word,那看看DocX吧。下面跟著小編一起來學習學習吧。

前言

相信大家應該都有所體會,在目前的軟件項目中,都會較多的使用到對文檔的操作,用于記錄和統(tǒng)計相關(guān)業(yè)務信息。由于系統(tǒng)自身提供了對文檔的相關(guān)操作,所以在一定程度上極大的簡化了軟件使用者的工作量。

在.NET項目中如果用戶提出了相關(guān)文檔操作的需求,開發(fā)者較多的會使用到微軟自行提供的插件,在一定程度上簡化了開發(fā)人員的工作量,但是同時也給用戶帶來了一些困擾,例如需要安裝龐大的office,在用戶體驗性就會降低很多,并且在國內(nèi),很多人都還是使用wps,這就導致一部分只安裝了wps的使用者很是為難,在對Excel的操作方面,有一個NPOI組件。那么可能會有人問有沒有什么辦法讓這些困擾得到解決,答案是肯定的,那就是今天需要介紹的“DocX”組件,接下來我們就來了解一下這個組件的功能和用法。

一.DocX組件概述:

DocX是一個.NET庫,允許開發(fā)人員以簡單直觀的方式處理Word 2007/2010/2013文件。 DocX是快速,輕量級,最好的是它不需要安裝Microsoft Word或Office。DocX組件不僅可以完成對文檔的一般要求,例如創(chuàng)建文檔,創(chuàng)建表格和文本,并且還可以創(chuàng)建圖形報表。DocX使創(chuàng)建和操作文檔成為一個簡單的任務。

它不使用COM庫,也不需要安裝Microsoft Office。在使用DocX組件時,你需要安裝為了使用DocX是.NET框架4.0和Visual Studio 2010或更高版本。

   DocX的主要特點:

     (1).在文檔中插入,刪除或替換文本。所有標準文本格式都可用。 字體{系列,大小,顏色},粗體,斜體,下劃線,刪除線,腳本{子,超級},突出顯示。

     (2).段落屬性顯示。方向LeftToRightRightToLeft;縮進;比對。  

     (3).DocX也支持:圖片,超鏈接,表,頁眉和頁腳,自定義屬性。

  有關(guān)DocX組件的相關(guān)信息就介紹到這里,如果需要更加深入的了解相關(guān)信息,可以進入:https://docx.codeplex.com/。

二.DocX相關(guān)類和方法解析:

本文將結(jié)合DocX的源碼進行解析,使用.NET Reflector對DLL文件進行反編譯,以此查看源代碼。將DLL文件加入.NET Reflector中,點擊打開文件。 

1.DocX.Create() :創(chuàng)建文檔。

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:將數(shù)據(jù)插入表格。

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:創(chuàng)建棒形圖。

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組件的一些方法的一些簡單解析,如果需要知道更多的方法實現(xiàn)代碼,可自行進行下載查看。

三.DocX功能實現(xiàn)實例:

1.創(chuàng)建圖表:

  /// <summary>
  /// 創(chuàng)建棒形圖
  /// </summary>
  /// <param name="path">文檔路徑</param>
  /// <param name="dicValue">綁定數(shù)據(jù)</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圖形屬性設(shè)置,BarDirection圖形方向枚舉,BarGrouping圖形分組枚舉
     var c = new BarChart
     {
      BarDirection = BarDirection.Column,
      BarGrouping = BarGrouping.Standard,
      GapWidth = 400
     };
     //設(shè)置圖表圖例位置
     c.AddLegend(ChartLegendPosition.Bottom, false);
     //寫入圖標數(shù)據(jù)
     foreach (var chartData in dicValue)
     {
      var series = new Series(chartData.Key);
      series.Bind(chartData.Value, categoryName, valueName);
      c.AddSeries(series);
     }     
     // 設(shè)置文檔標題
     document.InsertParagraph(title).FontSize(20);
     document.InsertChart(c);
     document.Save();
     return true;
    }

   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message);
   }
  }

2.創(chuàng)建一個具有超鏈接、圖像和表的文檔。

  /// <summary>
  /// 創(chuàng)建一個具有超鏈接、圖像和表的文檔。
  /// </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.將指定內(nèi)容寫入文檔:

  /// <summary>
  /// 將指定內(nèi)容寫入文檔
  /// </summary>
  /// <param name="path">加載文件路徑</param>
  /// <param name="content">寫入文件內(nèi)容</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];
      // 將內(nèi)容寫入圖片.
      var b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
      //獲取此位圖的圖形對象,圖形對象提供繪圖功能。
      var g = Graphics.FromImage(b);
      // 畫字符串內(nèi)容
      g.DrawString
       (
        content,
        new Font("Tahoma", 20),
        Brushes.Blue,
        new PointF(0, 0)
       );
      // 使用創(chuàng)建\寫入流將該位圖保存到文檔中。
      b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
     }
     else
     {
      document.SaveAs(savePath);
     } 
    }

   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message);
   }
  }

總結(jié)

以上就是對DocX組件的API做了一個簡單的解析,并且附上一些創(chuàng)建文檔和創(chuàng)建圖表的方法供開發(fā)者參考。希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

  • IIS7 應用程序池的 托管管道模式與集成模式小結(jié)

    IIS7 應用程序池的 托管管道模式與集成模式小結(jié)

    而 IIS 7 完全整合 .NET 之后,架構(gòu)的處理順序有了很大的不同(如下圖),最主要的原因就是 ASP.NET 從 IIS 插件(ISAPI extension)的角色,進入了 IIS 核心,而且也能以 ASP.NET 模塊負責處理 IIS 7 的諸多類型要求。
    2011-02-02
  • .Net使用XtraGrid控件綁定數(shù)據(jù)

    .Net使用XtraGrid控件綁定數(shù)據(jù)

    這篇文章介紹了.Net使用XtraGrid控件綁定數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • 詳解asp.net core 依賴注入

    詳解asp.net core 依賴注入

    這篇文章主要介紹了詳解asp.net core 依賴注入的相關(guān)知識,文中講解非常詳細,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-06-06
  • ASP.NET?Core中的通用主機HostBuilder

    ASP.NET?Core中的通用主機HostBuilder

    這篇文章介紹了ASP.NET?Core中的通用主機HostBuilder,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • asp.net WebForm頁面間傳值方法

    asp.net WebForm頁面間傳值方法

    asp.net WebForm頁面間傳值方法...
    2006-07-07
  • WPF使用ValidationRules對MVVM架構(gòu)數(shù)據(jù)驗證

    WPF使用ValidationRules對MVVM架構(gòu)數(shù)據(jù)驗證

    這篇文章介紹了WPF使用ValidationRules對MVVM架構(gòu)數(shù)據(jù)驗證的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-01-01
  • ASP.NET?Core?MVC中的布局(Layout)

    ASP.NET?Core?MVC中的布局(Layout)

    這篇文章介紹了ASP.NET?Core?MVC中的布局(Layout),文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • Linux下使用Jenkins自動化構(gòu)建.NET?Core應用

    Linux下使用Jenkins自動化構(gòu)建.NET?Core應用

    這篇文章介紹了Linux下使用Jenkins自動化構(gòu)建.NET?Core應用的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-04-04
  • 詳解ASP.NET Core中間件Middleware

    詳解ASP.NET Core中間件Middleware

    本文詳細講解了ASP.NET Core中間件Middleware,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-01-01
  • ASP.NET?Core?MVC中的模型(Model)

    ASP.NET?Core?MVC中的模型(Model)

    這篇文章介紹了ASP.NET?Core?MVC中的模型(Model),文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04

最新評論

凤翔县| 江安县| 新蔡县| 石狮市| 怀集县| 遂川县| 万山特区| 咸宁市| 洞头县| 友谊县| 南京市| 陈巴尔虎旗| 常宁市| 黄大仙区| 喀喇| 高平市| 娱乐| 德兴市| 石楼县| 德江县| 黑水县| 东安县| 五华县| 乌海市| 湘潭县| 海林市| 龙门县| 永济市| 湘乡市| 舟曲县| 仁布县| 易门县| 青冈县| 砚山县| 淮滨县| 汪清县| 夏津县| 四子王旗| 柘城县| 溆浦县| 石阡县|