チュートリアル
簡単にライブラリーを使用するためのチュートリアルコレクション
仕事上、2版の Word ドキュメントを受け取り、その違いを見つける必要に迫られることはよくあることです。特に、法令や教育などの分野では、文書の比較は重要であり、よく行われています。この記事では、Spire.Doc for .NET を使用して、C# と VB.NET で2つの Word ドキュメントを比較する方法について学びます。
以下は、比較される2つの Word ドキュメントのスクリーンショットです。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
比較結果を別の Word ドキュメントに保存すると、挿入、削除、書式の変更など、元のドキュメントに加えられたすべての変更を確認することができます。以下は、Spire.Doc for .NET を使用して、2つの Word ドキュメントを比較し、結果を別の Word ドキュメントに保存する手順です。
using Spire.Doc;
namespace CompareDocuments
{
class Program
{
static void Main(string[] args)
{
//Wordドキュメントを読み込む
Document doc1 = new Document("C:\\Sample1.docx");
//もう一方のWordドキュメントを読み込む
Document doc2 = new Document("C:\\Sample2.docx");
//Compare two documents
doc1.Compare(doc2, "桜桃子");
//Save the differences in a third document
doc1.SaveToFile("違い.docx", FileFormat.Docx2013);
doc1.Dispose();
}
}
}
Imports Spire.Doc
Namespace CompareDocuments
Class Program
Shared Sub Main(ByVal args() As String)
'Wordドキュメントを読み込む
Dim doc1 As Document = New Document("C:\\Sample1.docx")
'もう一方のWordドキュメントを読み込む
Dim doc2 As Document = New Document("C:\\Sample2.docx")
'Compare two documents
doc1.Compare(doc2, "桜桃子")
'Save the differences in a third document
doc1.SaveToFile("違い.docx", FileFormat.Docx2013)
doc1.Dispose()
End Sub
End Class
End Namespace
開発者は、すべての差分ではなく、挿入と削除の情報のみを取得したいと思うかもしれません。以下は、挿入と削除の情報を取得し、それらを2つの別々のリストに入れる手順です。
using Spire.Doc;
using Spire.Doc.Fields;
using System;
namespace GetDifferencesInList
{
class Program
{
static void Main(string[] args)
{
//Wordドキュメントを読み込む
Document doc1 = new Document("C:\\Sample1.docx");
//もう一方のWordドキュメントを読み込む
Document doc2 = new Document("C:\\Sample2.docx");
//2つのWordドキュメントを比較する
doc1.Compare(doc2, "桜桃子");
//改訂を取得する
DifferRevisions differRevisions = new DifferRevisions(doc1);
//挿入の改訂を返し、リストに入れる
var insetRevisionsList = differRevisions.InsertRevisions;
//削除の改訂を返し、リストに入れる
var deletRevisionsList = differRevisions.DeleteRevisions;
//2つのint型変数を作成する
int m = 0;
int n = 0;
//挿入改訂のリストをループする
for (int i = 0; i < insetRevisionsList.Count; i++)
{
if (insetRevisionsList[i] is TextRange)
{
m += 1;
//特定の改訂を取得し、その内容を取得する
TextRange textRange = insetRevisionsList[i] as TextRange;
Console.WriteLine("挿入 #" + m + ":" + textRange.Text);
}
}
Console.WriteLine("=====================");
//削除改訂のリストをループする
for (int i = 0; i < deletRevisionsList.Count; i++)
{
if (deletRevisionsList[i] is TextRange)
{
n += 1;
//特定の改訂を取得し、その内容を取得する
TextRange textRange = deletRevisionsList[i] as TextRange;
Console.WriteLine("削除 #" + n + ":" + textRange.Text);
}
}
Console.ReadKey();
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Fields
Imports System
Namespace GetDifferencesInList
Class Program
Shared Sub Main(ByVal args() As String)
'Wordドキュメントを読み込む
Dim doc1 As Document = New Document("C:\\Sample1.docx")
'もう一方のWordドキュメントを読み込む
Dim doc2 As Document = New Document("C:\\Sample2.docx")
'2つのWordドキュメントを比較する
doc1.Compare(doc2, "桜桃子")
'改訂を取得する
Dim differRevisions As DifferRevisions = New DifferRevisions(doc1)
'挿入の改訂を返し、リストに入れる
Dim insetRevisionsList As var = differRevisions.InsertRevisions
'削除の改訂を返し、リストに入れる
Dim deletRevisionsList As var = differRevisions.DeleteRevisions
'2つのint型変数を作成する
Dim m As Integer = 0
Dim n As Integer = 0
'挿入改訂のリストをループする
Dim i As Integer
For i = 0 To insetRevisionsList.Count - 1 Step i + 1
If TypeOf insetRevisionsList(i) Is TextRange Then
m += 1
'特定の改訂を取得し、その内容を取得する
Dim textRange As TextRange = insetRevisionsList(i) As TextRange
Console.WriteLine("挿入 #" + m + ":" + textRange.Text)
End If
Next
Console.WriteLine("=====================")
'削除改訂のリストをループする
Dim i As Integer
For i = 0 To deletRevisionsList.Count - 1 Step i + 1
If TypeOf deletRevisionsList(i) Is TextRange Then
n += 1
'特定の改訂を取得し、その内容を取得する
Dim textRange As TextRange = deletRevisionsList(i) As TextRange
Console.WriteLine("削除 #" + n + ":" + textRange.Text)
End If
Next
Console.ReadKey()
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word ドキュメントが今日最も人気のあるドキュメントのファイル形式の1つであることに疑いはありません。なぜなら、Word ドキュメントは、手紙、備忘録、報告書、期末論文、小説、雑誌などの生成に最適なファイル形式だからです。この記事では、Spire.Doc for .NET を使用して、最初から簡単な Word ドキュメントを作成する方法について説明します。
Spire.Doc for .NET は、Word ドキュメントのモデルを表現する Document クラスを提供します。この クラス を使用して、既存のドキュメントを読んだり編集したり、新しいドキュメントを作成したりすることができます。Word ドキュメントは、少なくとも1つのセクション(Section クラスで表現)を含んでいなければならず、各セクションは、段落、表、ヘッダー、フッターなどの Word の基本要素の容器である。以下の表は、このチュートリアルに含まれる重要なクラスとメソッドの一覧です。
プロパティ/メソッド | 説明 |
Document クラス | Word ドキュメントのモデルを表します。 |
Section クラス | Word ドキュメント内のセクションを表します。 |
Paragraph クラス | セクション内の段落を表す。 |
ParagraphStyle クラス | 段落に適用できる文字の書式情報を定義する。 |
Section.AddParagraph() メソッド | セクションに段落を追加します。 |
Paragraph.AppendText() メソッド | 段落の末尾にテキストを追加します。 |
Paragraph.ApplyStyle() メソッド | 段落にスタイルを適用します。 |
Document.SaveToFile() メソッド | ドキュメントを doc または docx の拡張子を持つ Word ファイルに保存します。この方法は、PDF、XPS、HTML、PLC などへの保存にも対応しています。 |
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
以下では、Spire.Doc for .NET を使用して、いくつかの段落を含む簡単な Word ドキュメントを作成する手順を説明します。
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace CreateWordDocument
{
class Program
{
static void Main(string[] args)
{
//Documentクラスのオブジェクトを作成する
Document doc = new Document();
//セクションを追加する
Section section = doc.AddSection();
//ページの余白を設定する
section.PageSetup.Margins.All = 40f;
//タイトルとして段落を追加する
Paragraph titleParagraph = section.AddParagraph();
titleParagraph.AppendText("Spire.Doc for .NETの紹介");
//本文として2つの段落を追加する
Paragraph bodyParagraph_1 = section.AddParagraph();
bodyParagraph_1.AppendText("Spire.Doc for .NET は、開発者が .NET " +
"(Target .NET Framework、.NET Core、.NET Standard、.NET 5.0、.NET 6.0、 Xamarin & Mono Android) プラットホームから " +
"Word の文書ファイルを迅速かつ高品質で作成・編集・変換・参照・印刷するために設計された専門的な Word.NET ライブラリです。");
Paragraph bodyParagraph_2 = section.AddParagraph();
bodyParagraph_2.AppendText("Spire.Doc for .NET は独立した Word.NET コンポーネントなので、" +
"Microsoft Office や Microsoft Word を実行環境にインストールする必要はありません。" +
"また、任意の開発者の .NET アプリケーションに Microsoft Word 文書作成機能を組み入れることができます。");
//タイトル段落のスタイルを作成する
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "titleStyle";
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Purple;
style1.CharacterFormat.FontName = "Yu Mincho";
style1.CharacterFormat.FontSize = 12;
doc.Styles.Add(style1);
titleParagraph.ApplyStyle("titleStyle");
//本文の段落のスタイルを作成する
ParagraphStyle style2 = new ParagraphStyle(doc);
style2.Name = "paraStyle";
style2.CharacterFormat.FontName = "Yu Mincho";
style2.CharacterFormat.FontSize = 12;
doc.Styles.Add(style2);
bodyParagraph_1.ApplyStyle("paraStyle");
bodyParagraph_2.ApplyStyle("paraStyle");
//段落の水平方向の配置を設定する
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
//最初の行のインデントを設定する
bodyParagraph_1.Format.FirstLineIndent = 30;
bodyParagraph_2.Format.FirstLineIndent = 30;
//段落後の間隔を設定する
titleParagraph.Format.AfterSpacing = 10;
bodyParagraph_1.Format.AfterSpacing = 10;
//ドキュメントを保存する
doc.SaveToFile("Wordドキュメント.docx", FileFormat.Docx2013);
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Namespace CreateWordDocument
Class Program
Shared Sub Main(ByVal args() As String)
'Documentクラスのオブジェクトを作成する
Dim doc As New Document()
'セクションを追加する
Dim section As Section = doc.AddSection()
'ページの余白を設定する
section.PageSetup.Margins.All = 40.0F
'タイトルとして段落を追加する
Dim titleParagraph As Paragraph = section.AddParagraph()
titleParagraph.AppendText("Spire.Doc for .NETの紹介")
'本文として2つの段落を追加する
Dim bodyParagraph_1 As Paragraph = section.AddParagraph()
bodyParagraph_1.AppendText("Spire.Doc for .NET は、開発者が .NET " +
"(Target .NET Framework、.NET Core、.NET Standard、.NET 5.0、.NET 6.0、 Xamarin & Mono Android) プラットホームから " +
"Word の文書ファイルを迅速かつ高品質で作成・編集・変換・参照・印刷するために設計された専門的な Word.NET ライブラリです。")
Dim bodyParagraph_2 As Paragraph = section.AddParagraph()
bodyParagraph_2.AppendText("Spire.Doc for .NET は独立した Word.NET コンポーネントなので、" +
"Microsoft Office や Microsoft Word を実行環境にインストールする必要はありません。" +
"また、任意の開発者の .NET アプリケーションに Microsoft Word 文書作成機能を組み入れることができます。")
'タイトル段落のスタイルを作成する
Dim style1 As ParagraphStyle = New ParagraphStyle(doc)
style1.Name = "titleStyle"
style1.CharacterFormat.Bold = True
style1.CharacterFormat.TextColor = Color.Purple
style1.CharacterFormat.FontName = "Yu Mincho"
style1.CharacterFormat.FontSize = 12
doc.Styles.Add(style1)
titleParagraph.ApplyStyle("titleStyle")
'本文の段落のスタイルを作成する
Dim style2 As ParagraphStyle = New ParagraphStyle(doc)
style2.Name = "paraStyle"
style2.CharacterFormat.FontName = "Yu Mincho"
style2.CharacterFormat.FontSize = 12
doc.Styles.Add(style2)
bodyParagraph_1.ApplyStyle("paraStyle")
bodyParagraph_2.ApplyStyle("paraStyle")
'段落の水平方向の配置を設定する
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify
'最初の行のインデントを設定する
bodyParagraph_1.Format.FirstLineIndent = 30
bodyParagraph_2.Format.FirstLineIndent = 30
'段落後の間隔を設定する
titleParagraph.Format.AfterSpacing = 10
bodyParagraph_1.Format.AfterSpacing = 10
'ドキュメントを保存する
doc.SaveToFile("Wordドキュメント.docx", FileFormat.Docx2013)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word 文書のブックマークは、文書内の特定のセクションに迅速に移動するために便利です。ブックマークを使用すると、文書内に「マーカー」を作成して名前を付け、簡単にジャンプすることができます。これは、特に長い文書や複雑な文書を扱う際に役立ちます。
この記事では、C# で Spire.Doc for .NET ライブラリを使用して、Word 文書にブックマークを追加および削除する方法を説明します。
まず、Spire.Doc for.NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc を使用して、段落の先頭に BookmarkStart オブジェクトを挿入し、段落の終わりに BookmarkEnd オブジェクトを挿入することで、段落にブックマークを作成できます。ブックマークの開始点と終了点の間のスペースが定義されたブックマークとなり、必要に応じて参照・アクセスすることができます。
段落にブックマークを追加する手順は以下の通りです。
using Spire.Doc;
using Spire.Doc.Documents;
namespace AddBookmarkToParagraph
{
class Program
{
static void Main(string[] args)
{
// Documentオブジェクトを作成
Document doc = new Document();
// Wordファイルをロード
doc.LoadFromFile("Sample.docx");
// 指定された段落を取得
Paragraph paragraph = doc.Sections[0].Paragraphs[1];
// ブックマークの開始を作成
BookmarkStart start = paragraph.AppendBookmarkStart("段落ブックマーク");
// 段落の最初に挿入
paragraph.Items.Insert(0, start);
// 段落の最後にブックマークの終了を追加
paragraph.AppendBookmarkEnd("段落ブックマーク");
// ファイルを保存
doc.SaveToFile("output/段落にブックマークを追加.docx", FileFormat.Docx2019);
// リソースを解放
doc.Dispose();
}
}
}
特定のテキストにブックマークを追加するには、まず段落内のテキストとその位置を見つける必要があります。次に、テキストの前に BookmarkStart オブジェクトを、テキストの後ろに BookmarkEnd オブジェクトを挿入します。
Spire.Doc を使用して段落内の特定のテキストにブックマークを追加する手順は以下の通りです。
using Spire.Doc;
using Spire.Doc.Documents;
namespace AddBookmarkToText
{
class Program
{
static void Main(string[] args)
{
// Documentオブジェクトを作成
Document doc = new Document();
// Wordファイルをロード
doc.LoadFromFile("Sample.docx");
// 検索する文字列を指定
string stringToFind = "不換紙幣";
// ドキュメントから選択されたテキストを検索
TextSelection[] finds = doc.FindAllString(stringToFind, false, true);
TextSelection specificText = finds[0];
// テキストがある段落を見つける
Paragraph para = specificText.GetAsOneRange().OwnerParagraph;
// 段落内のテキストのインデックスを取得
int index = para.ChildObjects.IndexOf(specificText.GetAsOneRange());
// ブックマークの開始を作成
BookmarkStart start = para.AppendBookmarkStart("テキストブックマーク");
// インデックス位置にブックマークの開始を挿入
para.ChildObjects.Insert(index, start);
// ブックマークの終了を作成
BookmarkEnd end = para.AppendBookmarkEnd("テキストブックマーク");
// 選択されたテキストの最後にブックマークの終了を挿入
para.ChildObjects.Insert(index + 2, end);
// ドキュメントを別のファイルに保存
doc.SaveToFile("output/ブックマークをテキストに追加.docx", FileFormat.Docx2019);
// リソースを解放
doc.Dispose();
}
}
}
Word 文書から特定のブックマークまたはすべてのブックマークを削除するには、Bookmarks.Remove() メソッドまたは Bookmarks.Clear() メソッドを使用します。詳細な手順は以下の通りです。
using Spire.Doc;
namespace RemoveBookmarks
{
class Program
{
static void Main(string[] args)
{
// Documentオブジェクトを作成
Document doc = new Document();
// Wordファイルをロード
doc.LoadFromFile("output/ブックマークをテキストに追加.docx");
// インデックスで特定のブックマークを取得
Bookmark bookmark = doc.Bookmarks[0];
// ブックマークを削除
doc.Bookmarks.Remove(bookmark);
// すべてのブックマークを一度に削除
// doc.Bookmarks.Clear();
// ドキュメントを保存
doc.SaveToFile("output/ブックマークを削除.docx", FileFormat.Docx2019);
// リソースを解放
doc.Dispose();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
この記事では、C# プログラムコードを例として取り上げ、txt ファイルのコンテンツを読み取って Word 文書を生成する方法を紹介します。コードを編集する前に、次のコード環境を参照して構成を確認できます。
1、NuGet を介して dll をインストールする方法
1.1、Visual Studio で「ソリューションエクスプローラー」を開き、「参照」、「NuGet パッケージの管理」を右クリックし、「無料のSpire.Doc」を検索して、「インストール」をクリックします。プログラムのインストールが完了するのを待ちます。
1.2、以下を PM コンソールのインストールにコピーします。
Install-Package FreeSpire.Doc -Version 9.9.7
パッケージを手動でダウンロードして解凍し、BIN フォルダーで Spire.Doc.dll を見つけることができます。次に、Visual Studio で「ソリューションエクスプローラー」を開き、「参照」、「参照の追加」を右クリックして、プログラムへのローカルパスの BIN フォルダーにある dll ファイルへの参照を追加します。
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.IO;
using System.Text;
namespace CreateWordDocument_Doc
{
class Program
{
static void Main(string[] args)
{
//Documentクラスのオブジェクトをインスタンス化し、sectionとparagraphを追加する
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
//txtファイルを読み取る
StreamReader sr = new StreamReader("C:\\Users\\Administrator\\Desktop\\test.txt", Encoding.Default);
//段落スタイルを設定し、段落に適用する
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "titleStyle";
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Purple;
style1.CharacterFormat.FontName = "Yu Mincho";
style1.CharacterFormat.FontSize = 12;
doc.Styles.Add(style1);
paragraph.ApplyStyle("titleStyle");
string line;
while ((line = sr.ReadLine()) != null)
{
paragraph.AppendText(line);//段落にtxtを書く
}
//docx形式でWordとして保存する
doc.SaveToFile("addTxttoWord.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("addTxttoWord.docx");
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.IO
Imports System.Text
Namespace CreateWordDocument_Doc
Class Program
Shared Sub Main(ByVal args() As String)
'Documentクラスのオブジェクトをインスタンス化し、sectionとparagraphを追加する
Document doc = New Document()
Dim section As Section = doc.AddSection()
Dim paragraph As Paragraph = section.AddParagraph()
'txtファイルを読み取る
Dim sr As StreamReader =
New StreamReader("C:\\Users\\Administrator\\Desktop\\test.txt",Encoding.Default)
'段落スタイルを設定し、段落に適用する
Dim style1 As ParagraphStyle = New ParagraphStyle(doc)
style1.Name = "titleStyle"
style1.CharacterFormat.Bold = True
style1.CharacterFormat.TextColor = Color.Purple
style1.CharacterFormat.FontName = "Yu Mincho"
style1.CharacterFormat.FontSize = 12
doc.Styles.Add(style1)
paragraph.ApplyStyle("titleStyle")
Dim line As String
While Not(line = sr.ReadLine()) Is Nothing
paragraph.AppendText(line)'段落にtxtを書く
End While
'docx形式でWordとして保存する
doc.SaveToFile("addTxttoWord.docx", FileFormat.Docx2013)
System.Diagnostics.Process.Start("addTxttoWord.docx")
End Sub
End Class
End Namespace
生成したドキュメントの効果は以下のようになります:
以上は今回の TXT を読み取って Word 文書を生成する記事でした、最後まで読んでいただきありがとうございます。
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30日間有効な一時ライセンスを取得してください。