チュートリアル
簡単にライブラリーを使用するためのチュートリアルコレクション
Word 文書を扱う際、ハイパーリンクを一括抽出することは実用的な用途が多くあります。技術文書や製品マニュアルから手動で URL を抽出するのは非効率であり、抜けや誤りが発生しやすいです。これを解決するため、本記事では C# を使用し、文書要素を解析することでハイパーリンクのアンカーテキスト、対応する URL、およびヒントを正確に抽出する自動化ソリューションを紹介します。抽出したハイパーリンクデータは、データ分析、SEO 最適化などの用途に活用できます。
以下のセクションでは、Spire.Doc for .NET を使用して C# で Word 文書からハイパーリンクを抽出する方法を解説します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Word 文書では、ハイパーリンクはフィールドとして格納されています。これを抽出するには、まずすべてのフィールドオブジェクトを特定し、それぞれのオブジェクトが Field クラスのインスタンスであるかを確認します。その後、Field オブジェクトの Type プロパティが FieldType.FieldHyperlink に等しいかをチェックすることで、ハイパーリンクフィールドを抽出できます。
ハイパーリンクを特定した後、Field.FieldText プロパティを使用してハイパーリンクのアンカーテキストを取得し、Field.GetFieldCode() メソッドを使用して以下の形式のフィールドコードを取得できます。
ハイパーリンクの種類 | フィールドコードの例 |
標準ハイパーリンク | HYPERLINK "https://www.example.com/example" |
ヒント付きハイパーリンク | HYPERLINK "https://www.example.com/example" \o "ScreenTip" |
フィールドコードを解析することで、ハイパーリンクの URL とヒントのテキストを取得でき、完全なハイパーリンク情報を抽出できます。
C# を使用して Word 文書からすべてのハイパーリンクを抽出する手順
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ExtractWordHyperlink
{
class Program
{
static void Main(string[] args)
{
// ドキュメントのインスタンスを作成
Document doc = new Document();
// Word ドキュメントを読み込む
doc.LoadFromFile("Sample.docx");
// ハイパーリンク情報を格納するための文字列リストを作成
List<string> hyperlinkInfoList = new List<string>();
// ドキュメント内のセクションを反復処理
foreach (Section section in doc.Sections)
{
// セクション内の子オブジェクトを反復処理
foreach (DocumentObject secObj in section.Body.ChildObjects)
{
// 現在のドキュメントオブジェクトが段落インスタンスか確認
if (secObj is Paragraph paragraph)
{
// 段落内の子オブジェクトを反復処理
foreach (DocumentObject paraObj in paragraph.ChildObjects)
{
// 現在の子オブジェクトがフィールドか確認
if (paraObj is Field field && field.Type == FieldType.FieldHyperlink)
{
string hyperlinkInfo = "";
// アンカーテキストを取得
string anchorText = field.FieldText;
// フィールドコードを取得
string fieldCode = field.GetFieldCode();
// フィールドコードからURLを取得
string url = fieldCode.Split('"')[1];
// ScreenTip があるか確認
if (fieldCode.Contains("\\o"))
{
// ヒント テキストを取得
string screenTip = fieldCode.Split("\"")[3].Trim();
// 情報を統合
hyperlinkInfo += $"アンカーテキスト: {anchorText}\nURL: {url}\nヒント: {screenTip}";
}
else
{
hyperlinkInfo += $"アンカーテキスト: {anchorText}\nURL: {url}";
}
hyperlinkInfo += "\n";
// ハイパーリンク情報をリストに追加
hyperlinkInfoList.Add(hyperlinkInfo);
}
}
}
}
}
// 抽出したハイパーリンク情報をテキストファイルに書き込む
File.WriteAllLines("output/抽出したハイパーリンク.txt", hyperlinkInfoList);
doc.Close();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word 文書のハイパーリンクは、読者がウェブサイトや他の文書に移動できるクリック可能なリンクです。ハイパーリンクは有用な追加情報を提供することがありますが、場合によっては注意を逸らしたり、不要に煩わしいと感じることもあります。そのため、ハイパーリンクを削除したい場合があります。この記事では、C# を使用して、Spire.Doc for .NET で Word ドキュメントからハイパーリンクを削除する方法を説明します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Word文書内のすべてのハイパーリンクを一度に削除するには、まず文書内のすべてのハイパーリンクを見つけ、それらを一括して処理するカスタムメソッド FlattenHyperlinks() を作成する必要があります。以下はその詳細な手順です。
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace removeWordHyperlink
{
class Program
{
static void Main(string[] args)
{
// ドキュメントインスタンスを作成
Document doc = new Document();
// サンプルのWordドキュメントを読み込む
doc.LoadFromFile("Sample.docx");
// すべてのハイパーリンクを探す
List<Field> hyperlinks = FindAllHyperlinks(doc);
// すべてのハイパーリンクをフラット化する
for (int i = hyperlinks.Count - 1; i >= 0; i--)
{
FlattenHyperlinks(hyperlinks[i]);
}
// 結果のドキュメントを保存する
doc.SaveToFile("output/RemoveHyperlinks.docx", FileFormat.Docx);
}
// サンプルドキュメントからすべてのハイパーリンクを取得するためのFindAllHyperlinks()メソッドを作成
private static List<Field> FindAllHyperlinks(Document document)
{
List<Field> hyperlinks = new List<Field>();
// セクション内の項目を繰り返し処理して、すべてのハイパーリンクを探す
foreach (Section section in document.Sections)
{
foreach (DocumentObject sec in section.Body.ChildObjects)
{
if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
{
foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
{
if (para.DocumentObjectType == DocumentObjectType.Field)
{
Field field = para as Field;
if (field.Type == FieldType.FieldHyperlink)
{
hyperlinks.Add(field);
}
}
}
}
}
}
return hyperlinks;
}
// ハイパーリンクフィールドをフラット化するためのFlattenHyperlinks()メソッドを作成
private static void FlattenHyperlinks(Field field)
{
int ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
int fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
Paragraph sepOwnerPara = field.Separator.OwnerParagraph;
int sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
int sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
int endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
int endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);
FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);
field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);
for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
{
if (i == sepOwnerParaIndex && i == ownerParaIndex)
{
for (int j = sepIndex; j >= fieldIndex; j--)
{
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
}
else if (i == ownerParaIndex)
{
for (int j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--)
{
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
}
else if (i == sepOwnerParaIndex)
{
for (int j = sepIndex; j >= 0; j--)
{
sepOwnerPara.ChildObjects.RemoveAt(j);
}
}
else
{
field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
}
}
}
// ハイパーリンクのフォントカラーと下線フォーマットを削除するためのFormatFieldResultText()メソッドを作成
private static void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
{
for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
{
Paragraph para = ownerBody.ChildObjects[i] as Paragraph;
if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
{
for (int j = sepIndex + 1; j < endIndex; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else if (i == sepOwnerParaIndex)
{
for (int j = sepIndex + 1; j < para.ChildObjects.Count; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else if (i == endOwnerParaIndex)
{
for (int j = 0; j < endIndex; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else
{
for (int j = 0; j < para.ChildObjects.Count; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
}
}
// テキストの色を黒に変更し、下線を削除するためのFormatText()メソッドを作成
private static void FormatText(TextRange tr)
{
// テキストの色を黒に設定
tr.CharacterFormat.TextColor = Color.Black;
// テキストの下線スタイルをなしに設定
tr.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
Word ドキュメント内のハイパーリンクを使用すると、読者はドキュメントの任意の位置、ファイル、Web サイト、または電子メールにジャンプすることができます。ハイパーリンクを使用すると、読者は関連する情報へすばやく簡単に移動することができます。この記事では、Spire.Doc for .NET を使用して Word ドキュメント内のテキストや画像にハイパーリンクを挿入する方法について説明します。
まず、Spire.Doc for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.Doc
Spire.Doc では、段落内のテキストや画像に Web リンク、メールリンク、ファイルリンク、ブックマークリンクを追加する Paragraph.AppendHyperlink() メソッドを提供しています。以下は、その詳細な手順です。
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace InsertHyperlinks
{
internal class Program
{
static void Main(string[] args)
{
//Wordドキュメントを作成する
Document doc = new Document();
//セクションを追加する
Section section = doc.AddSection();
//段落を追加する
Paragraph paragraph = section.AddParagraph();
paragraph.AppendHyperlink("https://jp.e-iceblue.com/", "公式サイト", HyperlinkType.WebLink);
//改行を追加する
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
//メールリンクを追加する
paragraph.AppendHyperlink("mailto:support @e-iceblue.com", "メールでのお問い合わせ", HyperlinkType.EMailLink);
//改行を追加する
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
//ファイルリンクを追加する
string filePath = @"C:\レポート.xlsx";
paragraph.AppendHyperlink(filePath, "クリックするとレポートが開きます", HyperlinkType.FileLink);
//改行を追加する
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
//別のセクションを追加し、ブックマークを作成する
Section section2 = doc.AddSection();
Paragraph bookmarkParagrapg = section2.AddParagraph();
bookmarkParagrapg.AppendText("これは1つのブックマークです");
BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("私のブックマーク");
bookmarkParagrapg.Items.Insert(0, start);
bookmarkParagrapg.AppendBookmarkEnd("私のブックマーク");
//ブックマークへのリンクを追加する
paragraph.AppendHyperlink("私のブックマーク", "このドキュメントの中の特定の位置へジャンプする", HyperlinkType.Bookmark);
//改行を追加する
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
//画像に基づくハイパーリンクを追加する
Image image = Image.FromFile(@"C:\.net.png");
Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
paragraph.AppendHyperlink("https://docs.microsoft.com/ja-jp/dotnet/", picture, HyperlinkType.WebLink);
//ドキュメントを保存する
doc.SaveToFile("ハイパーリンクの挿入.docx", FileFormat.Docx2013);
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Namespace InsertHyperlinks
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Wordドキュメントを作成する
Dim doc As Document = New Document()
'セクションを追加する
Dim section As Section = doc.AddSection()
'段落を追加する
Dim paragraph As Paragraph = section.AddParagraph()
paragraph.AppendHyperlink("https://jp.e-iceblue.com/", "公式サイト", HyperlinkType.WebLink)
'改行を追加する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)
'メールリンクを追加する
paragraph.AppendHyperlink("mailto:support @e-iceblue.com", "メールでのお問い合わせ", HyperlinkType.EMailLink)
'改行を追加する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)
'ファイルリンクを追加する
Dim filePath As String = "C:\レポート.xlsx"
paragraph.AppendHyperlink(filePath, "クリックするとレポートが開きます", HyperlinkType.FileLink)
'改行を追加する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)
'別のセクションを追加し、ブックマークを作成する
Dim section2 As Section = doc.AddSection()
Dim bookmarkParagrapg As Paragraph = section2.AddParagraph()
bookmarkParagrapg.AppendText("これは1つのブックマークです")
Dim start As BookmarkStart = bookmarkParagrapg.AppendBookmarkStart("私のブックマーク")
bookmarkParagrapg.Items.Insert(0, start)
bookmarkParagrapg.AppendBookmarkEnd("私のブックマーク")
'ブックマークへのリンクを追加する
paragraph.AppendHyperlink("私のブックマーク", "このドキュメントの中の特定の位置へジャンプする", HyperlinkType.Bookmark)
'改行を追加する
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)
'画像に基づくハイパーリンクを追加する
Dim image As Image = Image.FromFile("C:\.net.png")
Dim picture As Spire.Doc.Fields.DocPicture = paragraph.AppendPicture(image)
paragraph.AppendHyperlink("https://docs.microsoft.com/ja-jp/dotnet/", picture, HyperlinkType.WebLink)
'ドキュメントを保存する
doc.SaveToFile("ハイパーリンクの挿入.docx", FileFormat.Docx2013)
End Sub
End Class
End Namespace
ドキュメント内の既存のテキストにハイパーリンクを追加するのは、少し複雑です。対象となる文字列を見つけ、それをハイパーリンクフィールドに置き換える必要があります。以下はその手順です。
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
namespace InsertHyperlinks
{
internal class Program
{
static void Main(string[] args)
{
//Documentクラスのオブジェクトを作成する
Document document = new Document();
//Wordドキュメントを読み込む
document.LoadFromFile(@"C:\例.docx");
//ドキュメント内の「.NET Framework」文字列をすべて検索する
TextSelection[] selections = document.FindAllString(".NET Framework", true, true);
//2番目に見つかった文字列を取得する
TextRange range = selections[1].GetAsOneRange();
//この文字列が含まれる段落を取得する
Paragraph parapgraph = range.OwnerParagraph;
//段落内のこの文字列の位置を取得する
int index = parapgraph.Items.IndexOf(range);
//この文字列を段落から削除する
parapgraph.Items.Remove(range);
//ハイパーリンクフィールドを作成する
Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
field.Type = Spire.Doc.FieldType.FieldHyperlink;
Hyperlink hyperlink = new Hyperlink(field);
hyperlink.Type = HyperlinkType.WebLink;
hyperlink.Uri = "https://ja.wikipedia.org/wiki/.NET_Framework";
parapgraph.Items.Insert(index, field);
//段落にフィールドマーク「start」を挿入する
IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
(start as FieldMark).Type = FieldMarkType.FieldSeparator;
parapgraph.Items.Insert(index + 1, start);
//2つのフィールドマークの間にテキスト範囲を挿入する
ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
textRange.Text = ".NET Framework";
textRange.CharacterFormat.FontName = range.CharacterFormat.FontName;
textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
parapgraph.Items.Insert(index + 2, textRange);
//段落にフィールドマーク「end」を挿入する
IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
(end as FieldMark).Type = FieldMarkType.FieldEnd;
parapgraph.Items.Insert(index + 3, end);
//ドキュメントを保存する
document.SaveToFile("ハイパーリンクの追加.docx", Spire.Doc.FileFormat.Docx);
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Interface
Namespace InsertHyperlinks
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Documentクラスのオブジェクトを作成する
Dim document As Document = New Document()
'Wordドキュメントを読み込む
document.LoadFromFile("C:\例.docx")
'ドキュメント内の「.NET Framework」文字列をすべて検索する
Dim selections() As TextSelection = document.FindAllString(".NET Framework", True, True)
'2番目に見つかった文字列を取得する
Dim range As TextRange = selections(1).GetAsOneRange()
'この文字列が含まれる段落を取得する
Dim parapgraph As Paragraph = range.OwnerParagraph
'段落内のこの文字列の位置を取得する
Dim index As Integer = parapgraph.Items.IndexOf(range)
'この文字列を段落から削除する
parapgraph.Items.Remove(range)
'ハイパーリンクフィールドを作成する
Dim field As Spire.Doc.Fields.Field = New Spire.Doc.Fields.Field(document)
field.Type = Spire.Doc.FieldType.FieldHyperlink
Dim hyperlink As Hyperlink = New Hyperlink(field)
hyperlink.Type = HyperlinkType.WebLink
hyperlink.Uri = "https://ja.wikipedia.org/wiki/.NET_Framework"
parapgraph.Items.Insert(index, field)
'段落にフィールドマーク「start」を挿入する
Dim start As IParagraphBase = document.CreateParagraphItem(ParagraphItemType.FieldMark)
(start as FieldMark).Type = FieldMarkType.FieldSeparator
parapgraph.Items.Insert(index + 1, start)
'2つのフィールドマークの間にテキスト範囲を挿入する
Dim textRange As ITextRange = New Spire.Doc.Fields.TextRange(document)
textRange.Text = ".NET Framework"
textRange.CharacterFormat.FontName = range.CharacterFormat.FontName
textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue
textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single
parapgraph.Items.Insert(index + 2, textRange)
'段落にフィールドマーク「end」を挿入する
Dim nd As IParagraphBase = document.CreateParagraphItem(ParagraphItemType.FieldMark)
(nd as FieldMark).Type = FieldMarkType.FieldEnd
parapgraph.Items.Insert(index + 3, nd)
'ドキュメントを保存する
document.SaveToFile("ハイパーリンクの追加.docx", Spire.Doc.FileFormat.Docx)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。