.NETにおけるオープンソース文書操作コンポーネントDocXの紹介と使用
12210 ワード
前言
現在のソフトウェアプロジェクトでは、関連業務情報の記録や統計にドキュメントの操作が多く使われていることをご存知でしょうか.システム自体がドキュメントに関する操作を提供するため、ソフトウェア使用者の作業量をある程度簡素化することができる.
.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).段落属性表示.方向
(3).DocXでは、画像、ハイパーリンク、テーブル、ヘッダー、フッター、カスタムプロパティもサポートされています.
DocXコンポーネントに関する情報はここまでです.詳細な情報が必要な場合は、次の操作を行います.https://docx.codeplex.com/.
二.DocX関連クラスと方法の解析:
ここではDocXのソースコードを解析し、.NET Reflectorを使用してDLLファイルを逆コンパイルし、ソースコードを表示します.DLLファイルを.NET Reflectorに追加し、クリックしてファイルを開きます.
1.DocX.CReate():ドキュメントを作成します.
2.Paragraph.Append:段落に情報を追加します.
3.Table.InsertTable AfterSelf:テーブルにデータを挿入します.
4.CustomProperties:カスタム属性.
5.BarChart:棒グラフを作成します.
6.ChartのAddLegend()、AddSeries()、RemoveLegend()メソッド解析:
以上はDocXコンポーネントのいくつかの方法の簡単な解析であり、より多くの方法実装コードを知る必要がある場合は、自分でダウンロードして表示することができます.
三.DocX機能の実現例:
1.グラフの作成:
2.ハイパーリンク、画像、テーブルを持つドキュメントを作成します.
3.指定された内容をドキュメントに書き込みます.
まとめ
以上、DocXコンポーネントのAPIを簡単に解析し、開発者の参考にするためにドキュメントの作成とグラフの作成方法を添付しました.本文の内容はみんなの学习あるいは仕事に対して一定の助けをもたらすことができることを望んで、もし疑问があればみんなは伝言を残して交流することができます.
現在のソフトウェアプロジェクトでは、関連業務情報の記録や統計にドキュメントの操作が多く使われていることをご存知でしょうか.システム自体がドキュメントに関する操作を提供するため、ソフトウェア使用者の作業量をある程度簡素化することができる.
.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 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.InsertTable AfterSelf:テーブルにデータを挿入します.
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.CustomProperties:カスタム属性.
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);
}
}
まとめ
以上、DocXコンポーネントのAPIを簡単に解析し、開発者の参考にするためにドキュメントの作成とグラフの作成方法を添付しました.本文の内容はみんなの学习あるいは仕事に対して一定の助けをもたらすことができることを望んで、もし疑问があればみんなは伝言を残して交流することができます.