ライブ環境でテストする
ウォーターマークなしで本番環境でテストしてください。
必要な場所でいつでも動作します。
このガイドでは、既存のWord文書をインポートする方法、その内容を表示する方法、およびIronWord ライブラリ. このチュートリアルが終わるころには、以下のような翻訳が完成していることでしょう。ASP.NET Coreウェブアプリケーション
Word文書をアップロードして読む
これらのドキュメントの内容をテキストボックスに表示する
Docxファイルをエクスポート
このプロジェクトは、文書管理システム、レポートジェネレータ、Microsoft Wordファイルが関係するその他のシナリオなど、Word文書処理をWebアプリケーションに統合する必要がある開発者に最適です。
このチュートリアルに従うには、次のものが必要です:
.NET Core SDK 3.1以降。
これらの技術の専門家でなくてもご安心ください。!
IronWordは、開発者がMicrosoft Word文書をプログラムで読み取り、操作し、作成できるようにする.NETライブラリです。 Wordファイルでの作業を簡素化する高水準のAPIを提供しており、私たちのプロジェクトに最適です。
IronWordの主な特徴は以下の通りです:
Word文書を簡単にPDF文書に変換することで、最終的なWord文書をPDFファイルに変換し、簡単に共有することができます。
私たちが構築するものと使用するツールの概要がわかったところで、プロジェクトのセットアップに入りましょう。!
このセクションでは、新しいASP.NET Coreプロジェクトを作成し、IronWordで作業するために必要なパッケージをインストールします。
Visual Studio 2019以降を開いてください。
「Create a new project」をクリックしてください。
ASP.NET Core Web Application」を検索し、選択してください。
壊れた画像 Pixabayから追加。ファイルから選択するか、ここに画像をドラッグアンドドロップしてください。
「次へ」をクリックしてください。
プロジェクト名 "WordDocumentProcessor"(または任意の名前).
プロジェクトをセットアップしたので、IronWordライブラリを追加しましょう:
ソリューションエクスプローラーでプロジェクトを右クリックします。
NuGetパッケージの管理 "を選択します。
参照」タブで「IronWord」を検索してください。
壊れた画像 Pixabayから追加。ファイルから選択するか、ここに画像をドラッグアンドドロップしてください。
IronWordの公式パッケージをお探しください。
文書処理機能を組み込むために、既存の構造を更新してみましょう:
ドキュメント処理ロジックには、Controllersフォルダ内の既存のHomeController.csを使用します。
Views/Homeフォルダ内の既存のIndex.cshtmlビューを更新し、ドキュメントのアップロードと表示機能を追加します。
プロジェクトのセットアップとIronWordパッケージのインストールが完了したので、ドキュメントのインポートとエクスポート機能の実装を開始します。 HomeControllerに新しいメソッドを追加し、これらの機能を扱うためにIndexビューを修正します。 次のセクションでは、既存のコントローラとビューの構造を利用して、Word文書をインポートし、その内容を表示することに焦点を当てます。 メールマージ機能を追加することもできますが、この記事ではドキュメントのインポートとエクスポートに焦点を当てます。
このセクションでは、ASP.NET MVCアプリケーションでWord文書をインポートして処理する機能を実装する方法を探ります。 ユーザーインターフェースのデザインとバックエンドのコントローラロジックの両方をカバーします。
Word文書をインポートするためのユーザーインターフェイスは、直感的で視覚に訴えるように設計されています。 UIの主要コンポーネントを分解してみましょう:
アップロードエリアは、ユーザーがWord文書を選択し、アップロードするよう促す、インターフェイスの焦点です。 構成は以下の通りです:
<div class="upload-area">
<svg class="file-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
<p>Choose a Word document</p>
<label for="fileInput" class="choose-file">Choose File</label>
<p class="file-info">.DOC or .DOCX (MAX. 10MB)</p>
<button id="uploadBtn" class="upload-button">Upload and Process</button>
</div>
<div class="upload-area">
<svg class="file-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
<p>Choose a Word document</p>
<label for="fileInput" class="choose-file">Choose File</label>
<p class="file-info">.DOC or .DOCX (MAX. 10MB)</p>
<button id="uploadBtn" class="upload-button">Upload and Process</button>
</div>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<div class="upload-area"> <svg class="file-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path> <polyline points="14 2 14 8 20 8"></polyline> <line x1="16" y1="13" x2="8" y2="13"></line> <line x1="16" y1="17" x2="8" y2="17"></line> <polyline points="10 9 9 9 8 9"></polyline> </svg> <p> Choose a Word document</p> <label for="fileInput" class="choose-file"> Choose File</label> <p class="file-info">.DOC @or.DOCX(MAX. 10MB)</p> <button id="uploadBtn" class="upload-button"> Upload @and Process</button> </div>
このコードでは、ファイルアイコン、非表示のファイル入力、ファイル選択ボタンとして機能するスタイル付きラベルを使用して、視覚的に魅力的なアップロード領域を作成します。 また、使用可能なファイルタイプに関する情報と、アップロードと処理を開始するためのボタンも含まれています。
ドキュメントを処理した後、その内容は専用エリアに表示されます:
<div class="content-wrapper">
<h2>Document Content:</h2>
<div id="documentContent" class="content-area">
No content to display.
</div>
</div>
<div class="content-wrapper">
<h2>Document Content:</h2>
<div id="documentContent" class="content-area">
No content to display.
</div>
</div>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<div class="content-wrapper"> <h2> Document Content:</h2> <div id="documentContent" class="content-area"> No content @to display. </div> </div>
このセクションでは、処理されたドキュメントの内容を表示するためのスクロール可能な領域を提供します。
HomeControllerは、Word文書をインポートして処理するサーバー側のロジックを処理します。 それでは、主な方法を検証してみましょう:
このメソッドは、ファイルのアップロードと処理を担当します:
[HttpPost]
public IActionResult UploadAndProcess(IFormFile file)
{
if (file == null
file.Length == 0)
{
return Json(new { success = false, message = "No file uploaded." });
}
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (fileExtension != ".doc" && fileExtension != ".docx")
{
return Json(new { success = false, message = "Invalid file type. Please upload a .doc or .docx file." });
}
try
{
var tempFilePath = Path.GetTempFileName();
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
file.CopyTo(stream);
}
StringBuilder contentBuilder = new StringBuilder();
WordDocument doc = new WordDocument(tempFilePath);
foreach (Paragraph paragraph in doc.Paragraphs)
{
foreach (Text textRun in paragraph.Texts)
{
contentBuilder.AppendLine(textRun.Text);
}
contentBuilder.AppendLine(); // Add an extra line between paragraphs
}
System.IO.File.Delete(tempFilePath); // Clean up the temporary file
return Json(new { success = true, content = FormatContentAsHtml(contentBuilder.ToString()) });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing document");
return Json(new { success = false, message = "An error occurred while processing the document." });
}
}
[HttpPost]
public IActionResult UploadAndProcess(IFormFile file)
{
if (file == null
file.Length == 0)
{
return Json(new { success = false, message = "No file uploaded." });
}
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (fileExtension != ".doc" && fileExtension != ".docx")
{
return Json(new { success = false, message = "Invalid file type. Please upload a .doc or .docx file." });
}
try
{
var tempFilePath = Path.GetTempFileName();
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
file.CopyTo(stream);
}
StringBuilder contentBuilder = new StringBuilder();
WordDocument doc = new WordDocument(tempFilePath);
foreach (Paragraph paragraph in doc.Paragraphs)
{
foreach (Text textRun in paragraph.Texts)
{
contentBuilder.AppendLine(textRun.Text);
}
contentBuilder.AppendLine(); // Add an extra line between paragraphs
}
System.IO.File.Delete(tempFilePath); // Clean up the temporary file
return Json(new { success = true, content = FormatContentAsHtml(contentBuilder.ToString()) });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing document");
return Json(new { success = false, message = "An error occurred while processing the document." });
}
}
<HttpPost>
Public Function UploadAndProcess(ByVal file As IFormFile) As IActionResult
If file Is Nothing file.Length = 0 Then
Return Json(New With {
Key .success = False,
Key .message = "No file uploaded."
})
End If
Dim fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant()
If fileExtension <> ".doc" AndAlso fileExtension <> ".docx" Then
Return Json(New With {
Key .success = False,
Key .message = "Invalid file type. Please upload a .doc or .docx file."
})
End If
Try
Dim tempFilePath = Path.GetTempFileName()
Using stream = New FileStream(tempFilePath, FileMode.Create)
file.CopyTo(stream)
End Using
Dim contentBuilder As New StringBuilder()
Dim doc As New WordDocument(tempFilePath)
For Each paragraph As Paragraph In doc.Paragraphs
For Each textRun As Text In paragraph.Texts
contentBuilder.AppendLine(textRun.Text)
Next textRun
contentBuilder.AppendLine() ' Add an extra line between paragraphs
Next paragraph
System.IO.File.Delete(tempFilePath) ' Clean up the temporary file
Return Json(New With {
Key .success = True,
Key .content = FormatContentAsHtml(contentBuilder.ToString())
})
Catch ex As Exception
_logger.LogError(ex, "Error processing document")
Return Json(New With {
Key .success = False,
Key .message = "An error occurred while processing the document."
})
End Try
End Function
この方法では、以下のタスクを実行します:
アップロードされたファイルを検証し、正しいファイル形式であることを確認します。(DOCまたはDOCX)
正しいファイル拡張子のチェック
IronWordライブラリを使用してドキュメントを処理します。
このプライベートメソッドは、抽出されたコンテンツをHTMLにフォーマットします:
private string FormatContentAsHtml(string content)
{
var lines = content.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<div class='document-content'>");
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
htmlBuilder.Append("<p> </p>");
}
else
{
htmlBuilder.Append($"<p>{HttpUtility.HtmlEncode(line)}</p>");
}
}
htmlBuilder.Append("</div>");
return htmlBuilder.ToString();
}
private string FormatContentAsHtml(string content)
{
var lines = content.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<div class='document-content'>");
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
htmlBuilder.Append("<p> </p>");
}
else
{
htmlBuilder.Append($"<p>{HttpUtility.HtmlEncode(line)}</p>");
}
}
htmlBuilder.Append("</div>");
return htmlBuilder.ToString();
}
Private Function FormatContentAsHtml(ByVal content As String) As String
Dim lines = content.Split( { Environment.NewLine }, StringSplitOptions.None)
Dim htmlBuilder = New StringBuilder()
htmlBuilder.Append("<div class='document-content'>")
For Each line In lines
If String.IsNullOrWhiteSpace(line) Then
htmlBuilder.Append("<p> </p>")
Else
htmlBuilder.Append($"<p>{HttpUtility.HtmlEncode(line)}</p>")
End If
Next line
htmlBuilder.Append("</div>")
Return htmlBuilder.ToString()
End Function
この方法では、文書コンテンツがHTMLとして適切にフォーマットされ、各行が段落タグで囲まれ、空行が保持されます。
ファイルのアップロードを処理し、処理されたコンテンツを表示するには、JavaScriptを使用します:
uploadBtn.addEventListener('click', () => {
const file = fileInput.files[0];
if (!file) {
alert('Please select a file first.');
return;
}
const formData = new FormData();
formData.append('file', file);
uploadBtn.disabled = true;
uploadBtn.textContent = 'Processing...';
documentContent.innerHTML = 'Processing document...';
fetch('/Home/UploadAndProcess', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
documentContent.innerHTML = data.content;
} else {
documentContent.innerHTML = `<p>Error: ${data.message}</p>`;
}
})
.catch(error => {
console.error('Error:', error);
documentContent.innerHTML = '<p>An error occurred while processing the document.</p>';
})
.finally(() => {
uploadBtn.disabled = false;
uploadBtn.textContent = 'Upload and Process';
});
});
uploadBtn.addEventListener('click', () => {
const file = fileInput.files[0];
if (!file) {
alert('Please select a file first.');
return;
}
const formData = new FormData();
formData.append('file', file);
uploadBtn.disabled = true;
uploadBtn.textContent = 'Processing...';
documentContent.innerHTML = 'Processing document...';
fetch('/Home/UploadAndProcess', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
documentContent.innerHTML = data.content;
} else {
documentContent.innerHTML = `<p>Error: ${data.message}</p>`;
}
})
.catch(error => {
console.error('Error:', error);
documentContent.innerHTML = '<p>An error occurred while processing the document.</p>';
})
.finally(() => {
uploadBtn.disabled = false;
uploadBtn.textContent = 'Upload and Process';
});
});
uploadBtn.addEventListener( 'click', () =>
If True Then
const file = fileInput.files(0)
If Not file Then
alert( 'Please select a file first.');
Return
End If
const formData = New FormData()
formData.append( 'file', file);
uploadBtn.disabled = True
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' uploadBtn.textContent = 'Processing...'; documentContent.innerHTML = 'Processing document...'; fetch('/Home/UploadAndProcess', { method: 'POST', body: formData }).@then(response => response.json()).@then(data => { if(data.success) { documentContent.innerHTML = data.content; } else { documentContent.innerHTML = `<p> @Error: ${data.message}</p>`; } }).catch(@error => { console.@error('@Error:', @error); documentContent.innerHTML = '<p> An @error occurred while processing the document.</p>'; }).finally(() => { uploadBtn.disabled = False; uploadBtn.textContent = 'Upload @and Process'; }); });
このJavaScriptコードは、ファイルアップロードプロセスを処理し、処理のためにファイルをサーバーに送信し、処理されたコンテンツまたはエラーメッセージでUIを更新します。
このアプリケーションは、カスタムCSSを使用して、魅力的でユーザーフレンドリーなインターフェイスを作成します。
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f7f7f7;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
padding-top: 0.5rem;
}
h1 {
font-weight: 300;
color: #2c3e50;
text-align: center;
margin-bottom: 1rem;
}
.lead {
text-align: center;
color: #7f8c8d;
margin-bottom: 2rem;
}
.upload-area {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 2rem;
text-align: center;
margin-bottom: 2rem;
transition: all 0.3s ease;
}
.upload-area:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.file-icon {
width: 64px;
height: 64px;
margin-bottom: 1rem;
color: #3498db;
}
.choose-file {
background-color: #ecf0f1;
color: #2c3e50;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.choose-file:hover {
background-color: #d5dbdb;
}
.file-info {
font-size: 0.9em;
color: #95a5a6;
margin-top: 0.5rem;
}
.upload-button {
background-color: #3498db;
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
margin-top: 1rem;
}
.upload-button:hover {
background-color: #2980b9;
}
.content-wrapper {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 1rem;
margin-top: 2rem;
}
.content-area {
max-height: 300px;
overflow-y: auto;
padding: 1rem;
background-color: #f9f9f9;
border-radius: 4px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 14px;
line-height: 1.6;
}
.content-area::-webkit-scrollbar {
width: 8px;
}
.content-area::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.content-area::-webkit-scrollbar-thumb {
background: #bdc3c7;
border-radius: 4px;
}
.content-area::-webkit-scrollbar-thumb:hover {
background: #95a5a6;
}
.document-content p {
margin: 0 0 10px 0;
}
</style>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f7f7f7;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
padding-top: 0.5rem;
}
h1 {
font-weight: 300;
color: #2c3e50;
text-align: center;
margin-bottom: 1rem;
}
.lead {
text-align: center;
color: #7f8c8d;
margin-bottom: 2rem;
}
.upload-area {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 2rem;
text-align: center;
margin-bottom: 2rem;
transition: all 0.3s ease;
}
.upload-area:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.file-icon {
width: 64px;
height: 64px;
margin-bottom: 1rem;
color: #3498db;
}
.choose-file {
background-color: #ecf0f1;
color: #2c3e50;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.choose-file:hover {
background-color: #d5dbdb;
}
.file-info {
font-size: 0.9em;
color: #95a5a6;
margin-top: 0.5rem;
}
.upload-button {
background-color: #3498db;
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
margin-top: 1rem;
}
.upload-button:hover {
background-color: #2980b9;
}
.content-wrapper {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 1rem;
margin-top: 2rem;
}
.content-area {
max-height: 300px;
overflow-y: auto;
padding: 1rem;
background-color: #f9f9f9;
border-radius: 4px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 14px;
line-height: 1.6;
}
.content-area::-webkit-scrollbar {
width: 8px;
}
.content-area::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.content-area::-webkit-scrollbar-thumb {
background: #bdc3c7;
border-radius: 4px;
}
.content-area::-webkit-scrollbar-thumb:hover {
background: #95a5a6;
}
.document-content p {
margin: 0 0 10px 0;
}
</style>
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'(Of style) body
'{
''INSTANT VB TODO TASK: The following line uses invalid syntax:
'' font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f7f7f7; color: #333; } .container { max-width: 800px; margin: 0 auto; padding: 2rem; padding-top: 0.5rem; } h1 { font-weight: 300; color: #2c3e50; text-align: center; margin-bottom: 1rem; } .lead { text-align: center; color: #7f8c8d; margin-bottom: 2rem; } .upload-area { background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 2rem; text-align: center; margin-bottom: 2rem; transition: all 0.3s ease; } .upload-area:hover { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); } .file-icon { width: 64px; height: 64px; margin-bottom: 1rem; color: #3498db; } .choose-file { background-color: #ecf0f1; color: #2c3e50; border: none; padding: 0.5rem 1rem; border-radius: 4px; cursor: pointer; transition: background-color 0.3s ease; } .choose-file:hover { background-color: #d5dbdb; } .file-info { font-size: 0.9em; color: #95a5a6; margin-top: 0.5rem; } .upload-button { background-color: #3498db; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 4px; cursor: pointer; transition: background-color 0.3s ease; margin-top: 1rem; } .upload-button:hover { background-color: #2980b9; } .content-wrapper { background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 1rem; margin-top: 2rem; } .content-area { max-height: 300px; overflow-y: auto; padding: 1rem; background-color: #f9f9f9; border-radius: 4px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 14px; line-height: 1.6; } .content-area::-webkit-scrollbar { width: 8px; } .content-area::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; } .content-area::-webkit-scrollbar-thumb { background: #bdc3c7; border-radius: 4px; } .content-area::-webkit-scrollbar-thumb:hover { background: #95a5a6; } .document-content p { margin: 0 0 10px 0; } </style>
このCSSは、明るい配色でクリーンでモダンな印象を与えます。 アップロードエリアは、微妙なシャドウ効果のある白い背景が特徴で、コンテンツエリアはライトグレーの背景のスクロール可能なデザインです。 border-radiusとbox-shadowプロパティを使用することで、インターフェイス要素に深みと視覚的な面白さが加わります。
Word Document Processorの拡張を続けるにあたり、ドキュメントをエクスポートする機能を追加しましょう。 この機能により、ユーザーは当社のアプリケーションから新しいWord文書を生成できるようになります。
まず、ナビゲーションバーに「エクスポート」オプションを追加します。 Views/Sharedフォルダの_Layout.cshtmlファイルを開き、_Layout.cshtmlの場所を確認してください。
<li class="nav-item">
<a class="nav-link" id="exportLink" href="#" onclick="exportDocument(); return false;"><i class="fas fa-file-export"></i> Export</a>
</li>
<li class="nav-item">
<a class="nav-link" id="exportLink" href="#" onclick="exportDocument(); return false;"><i class="fas fa-file-export"></i> Export</a>
</li>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<li class="nav-item"> <a class="nav-link" id="exportLink" href="#" onclick="exportDocument(); return false;"><i class="fas fa-file-export"></i> Export</a> </li>
アイコンにFont Awesomeを使用しているので、CSSのリンクを
セクション このコードは、ナビゲーションバーに「エクスポート」リンクを追加します。 アイコンにFont Awesomeを使用し、exportDocumentを呼び出します。() クリックすると機能します。 href="#"**とreturn falseは、デフォルトのリンク動作を防ぎます。では、エクスポート処理を行うJavaScript関数を追加しましょう。 At the bottom of our _Layout.cshtml file, just before the closing tag, we'll add the following script:
<script>
function exportDocument() {
$.ajax({
url: '/Home/ExportWordDocument',
type: 'POST',
success: function (response) {
if (response.success) {
var fileName = prompt("Enter a name for the document (without extension):", "ExportedDocument");
if (fileName === null) {
return;
}
fileName = (fileName.trim()
"ExportedDocument").replace(/\.[^/.]+$/, "") + ".docx";
var a = document.createElement('a');
a.style.display = 'none';
a.href = '/Home/DownloadFile?tempFilePath=' + encodeURIComponent(response.tempFilePath) + '&userFileName=' + encodeURIComponent(fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
alert('Failed to export document: ' + response.message);
}
},
error: function () {
alert('An error occurred while exporting the document.');
}
});
}
</script>
<script>
function exportDocument() {
$.ajax({
url: '/Home/ExportWordDocument',
type: 'POST',
success: function (response) {
if (response.success) {
var fileName = prompt("Enter a name for the document (without extension):", "ExportedDocument");
if (fileName === null) {
return;
}
fileName = (fileName.trim()
"ExportedDocument").replace(/\.[^/.]+$/, "") + ".docx";
var a = document.createElement('a');
a.style.display = 'none';
a.href = '/Home/DownloadFile?tempFilePath=' + encodeURIComponent(response.tempFilePath) + '&userFileName=' + encodeURIComponent(fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
alert('Failed to export document: ' + response.message);
}
},
error: function () {
alert('An error occurred while exporting the document.');
}
});
}
</script>
Private Function exportDocument() As [function](Of script)
$.ajax({ url: '/Home/ExportWordDocument', type: 'POST', success: @function(response) { if(response.success) { var fileName = prompt("Enter a name for the document (without extension):", "ExportedDocument"); if(fileName === Nothing) { Return; } fileName = (fileName.trim() "ExportedDocument").replace(/\.[^/.]+$/, "") + ".docx"; var a = document.createElement("a"c); a.style.display = 'none'; a.href = '/Home/System.Nullable<DownloadFile>tempFilePath=' + encodeURIComponent(response.tempFilePath) + '&userFileName=' + encodeURIComponent(fileName); document.body.appendChild(a); a.click(); document.body.removeChild(a); } else { alert('Failed @to export document: ' + response.message); } }, @error: @function() { alert('An @error occurred while exporting the document.'); } });
End Function
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'</script>
このJavaScript関数は、Word文書を作成するためにサーバーにAJAX POSTリクエストを送信します。 成功すると、ユーザーにファイル名の入力を求め、ファイルをダウンロードするための一時的なリンクを作成します。リンクは自動的にクリックされ、DOMから削除されます。 いずれかの段階でエラーが発生した場合は、ユーザーにアラートが表示されます。
では、サーバーサイドのロジックを実装してみましょう。 Controllers フォルダ内の HomeController.cs ファイルを開きます。 エクスポート処理を処理するために、2つの新しいメソッドを追加します。
まず、Word文書を作成するメソッドを追加しましょう:
[HttpPost]
public IActionResult ExportWordDocument()
{
try
{
WordDocument doc = new WordDocument();
doc.AddText("Test Word");
string tempFileName = $"TempDoc_{Guid.NewGuid()}.docx";
string tempFilePath = Path.Combine(_environment.WebRootPath, "TempFiles", tempFileName);
Directory.CreateDirectory(Path.GetDirectoryName(tempFilePath));
doc.SaveAs(tempFilePath);
return Json(new { success = true, tempFilePath = $"/TempFiles/{tempFileName}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error exporting Word document");
return Json(new { success = false, message = "An error occurred while exporting the document." });
}
}
[HttpPost]
public IActionResult ExportWordDocument()
{
try
{
WordDocument doc = new WordDocument();
doc.AddText("Test Word");
string tempFileName = $"TempDoc_{Guid.NewGuid()}.docx";
string tempFilePath = Path.Combine(_environment.WebRootPath, "TempFiles", tempFileName);
Directory.CreateDirectory(Path.GetDirectoryName(tempFilePath));
doc.SaveAs(tempFilePath);
return Json(new { success = true, tempFilePath = $"/TempFiles/{tempFileName}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error exporting Word document");
return Json(new { success = false, message = "An error occurred while exporting the document." });
}
}
<HttpPost>
Public Function ExportWordDocument() As IActionResult
Try
Dim doc As New WordDocument()
doc.AddText("Test Word")
Dim tempFileName As String = $"TempDoc_{Guid.NewGuid()}.docx"
Dim tempFilePath As String = Path.Combine(_environment.WebRootPath, "TempFiles", tempFileName)
Directory.CreateDirectory(Path.GetDirectoryName(tempFilePath))
doc.SaveAs(tempFilePath)
Return Json(New With {
Key .success = True,
Key .tempFilePath = $"/TempFiles/{tempFileName}"
})
Catch ex As Exception
_logger.LogError(ex, "Error exporting Word document")
Return Json(New With {
Key .success = False,
Key .message = "An error occurred while exporting the document."
})
End Try
End Function
この方法では、IronWordライブラリを使用して新しいWord文書を作成し、テストテキストを追加して、一意の名前を付けて一時ファイルに保存します。 これは、成功ステータスと一時ファイルへのパスを持つJSONオブジェクトを返します。エラーが発生した場合は、例外をログに記録し、失敗メッセージを返します。
次に、ファイルのダウンロードを処理するメソッドを追加しましょう:
[HttpGet]
public IActionResult DownloadFile(string tempFilePath, string userFileName)
{
try
{
string fullPath = Path.Combine(_environment.WebRootPath, tempFilePath.TrimStart('/'));
if (!System.IO.File.Exists(fullPath))
{
return NotFound();
}
byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
System.IO.File.Delete(fullPath);
string fileName = !string.IsNullOrEmpty(userFileName) ? userFileName : "ExportedDocument.docx";
return File(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", fileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading file");
return BadRequest("An error occurred while downloading the file.");
}
}
[HttpGet]
public IActionResult DownloadFile(string tempFilePath, string userFileName)
{
try
{
string fullPath = Path.Combine(_environment.WebRootPath, tempFilePath.TrimStart('/'));
if (!System.IO.File.Exists(fullPath))
{
return NotFound();
}
byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
System.IO.File.Delete(fullPath);
string fileName = !string.IsNullOrEmpty(userFileName) ? userFileName : "ExportedDocument.docx";
return File(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", fileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading file");
return BadRequest("An error occurred while downloading the file.");
}
}
<HttpGet>
Public Function DownloadFile(ByVal tempFilePath As String, ByVal userFileName As String) As IActionResult
Try
Dim fullPath As String = Path.Combine(_environment.WebRootPath, tempFilePath.TrimStart("/"c))
If Not System.IO.File.Exists(fullPath) Then
Return NotFound()
End If
Dim fileBytes() As Byte = System.IO.File.ReadAllBytes(fullPath)
System.IO.File.Delete(fullPath)
Dim fileName As String = If(Not String.IsNullOrEmpty(userFileName), userFileName, "ExportedDocument.docx")
Return File(fileBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", fileName)
Catch ex As Exception
_logger.LogError(ex, "Error downloading file")
Return BadRequest("An error occurred while downloading the file.")
End Try
End Function
このメソッドは、ExportWordDocument によって作成された一時ファイルを取得し、その内容をバイト配列に読み込んでから、一時ファイルを削除します。このメソッドでは、指定されたユーザー・ファイル名、または指定されていない場合はデフォルトのファイル名が使用されます。 このメソッドは、ファイルの内容をダウンロード可能なWord文書として返します。 ファイルが見つからない場合やエラーが発生した場合は、適切なHTTP応答が返されます。
Word Document Processorの全体的なルック&フィールを改善するために、_Layout.cshtmlファイルにカスタムCSSを直接追加しました。実装したスタイルを確認してみましょう:
<style>
:root {
--primary-color: #3498db;
--text-color: #333;
--bg-color: #f8f9fa;
--nav-bg: #fff;
--nav-text: #2c3e50;
--nav-hover: #3498db;
}
body {
font-family: 'Segoe UI', sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
line-height: 1.6;
}
.navbar { background-color: var(--nav-bg); }
.navbar-brand {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary-color);
margin-right: 2rem;
}
.navbar-nav { margin-left: auto; }
.navbar-nav .nav-item { margin-left: 1rem; }
.navbar-nav .nav-link {
color: var(--nav-text);
font-weight: 500;
transition: all 0.3s ease;
padding: 0.5rem 1rem;
border-radius: 4px;
}
.navbar-nav .nav-link:hover, .navbar-nav .nav-link.active {
color: var(--primary-color);
background-color: rgba(52, 152, 219, 0.1);
}
.navbar-nav .nav-link i {
margin-right: 0.5rem;
font-size: 1.1em;
}
.centered-container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.footer {
background-color: var(--nav-bg);
border-top: 1px solid #ecf0f1;
font-size: 0.9em;
color: var(--nav-text);
}
.footer a {
color: var(--primary-color);
text-decoration: none;
transition: color 0.3s ease;
}
.footer a:hover { color: var(--nav-hover); }
@@media (max-width: 576px) {
.navbar-nav {
margin-left: 0;
margin-top: 1rem;
}
.navbar-nav .nav-item {
margin-left: 0;
margin-bottom: 0.5rem;
}
}
</style>
<style>
:root {
--primary-color: #3498db;
--text-color: #333;
--bg-color: #f8f9fa;
--nav-bg: #fff;
--nav-text: #2c3e50;
--nav-hover: #3498db;
}
body {
font-family: 'Segoe UI', sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
line-height: 1.6;
}
.navbar { background-color: var(--nav-bg); }
.navbar-brand {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary-color);
margin-right: 2rem;
}
.navbar-nav { margin-left: auto; }
.navbar-nav .nav-item { margin-left: 1rem; }
.navbar-nav .nav-link {
color: var(--nav-text);
font-weight: 500;
transition: all 0.3s ease;
padding: 0.5rem 1rem;
border-radius: 4px;
}
.navbar-nav .nav-link:hover, .navbar-nav .nav-link.active {
color: var(--primary-color);
background-color: rgba(52, 152, 219, 0.1);
}
.navbar-nav .nav-link i {
margin-right: 0.5rem;
font-size: 1.1em;
}
.centered-container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.footer {
background-color: var(--nav-bg);
border-top: 1px solid #ecf0f1;
font-size: 0.9em;
color: var(--nav-text);
}
.footer a {
color: var(--primary-color);
text-decoration: none;
transition: color 0.3s ease;
}
.footer a:hover { color: var(--nav-hover); }
@@media (max-width: 576px) {
.navbar-nav {
margin-left: 0;
margin-top: 1rem;
}
.navbar-nav .nav-item {
margin-left: 0;
margin-bottom: 0.5rem;
}
}
</style>
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'(Of style) :root
'{
' --primary-color: #3498db;
' --text-color: #333;
' --bg-color: #f8f9fa;
' --nav-bg: #fff;
' --nav-text: #2c3e50;
' --nav-hover: #3498db;
' }
body
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' font-family: 'Segoe UI', sans-serif; background-color: var(--bg-color); color: var(--text-color); line-height: 1.6; } .navbar { background-color: var(--nav-bg); } .navbar-brand { font-size: 1.5rem; font-weight: 700; color: var(--primary-color); margin-right: 2rem; } .navbar-nav { margin-left: auto; } .navbar-nav.nav-item { margin-left: 1rem; } .navbar-nav.nav-link { color: var(--nav-text); font-weight: 500; transition: all 0.3s ease; padding: 0.5rem 1rem; border-radius: 4px; } .navbar-nav.nav-link:hover, .navbar-nav.nav-link.active { color: var(--primary-color); background-color: rgba(52, 152, 219, 0.1); } .navbar-nav.nav-link i { margin-right: 0.5rem; font-size: 1.1em; } .centered-container { max-width: 800px; margin: 0 auto; padding: 2rem; } .footer { background-color: var(--nav-bg); border-top: 1px solid #ecf0f1; font-size: 0.9em; color: var(--nav-text); } .footer a { color: var(--primary-color); text-decoration: none; transition: color 0.3s ease; } .footer a:hover { color: var(--nav-hover); } @@media(max-width: 576px) { .navbar-nav { margin-left: 0; margin-top: 1rem; } .navbar-nav.nav-item { margin-left: 0; margin-bottom: 0.5rem; } } </style>
このCSSブロックは、アプリケーションの配色とレイアウトを定義します。 CSS変数を使用しています(カスタムプロパティ)アプリ全体で一貫したカラーパレットを作成します。スタイルは、ボディ、ナバー、フッターを含むさまざまな要素を対象とし、まとまりのあるデザインを保証します。 ホバー効果とアイコンの統合を特徴とする、クリーンでモダンなルックのナビゲーションを設定しました。 W
現在、私たちのアプリケーションはWord文書に重点を置いていますが、次のことが可能です。IronPDFPDF ドキュメントのサポートを含めることで、より幅広いファイル形式に対応できるように機能を拡張することができます。現在のWord形式のオプションに加えて、PDFファイルとして文書をエクスポートできるようにシステムを拡張することができる。
WordDocumentProcessorアプリケーションを実行することから始めましょう。 画像でわかるように、アプリケーションはブラウザで正常に読み込まれています。 インターフェースはクリーンでユーザーフレンドリーであり、上部のナビゲーションバーには「ホーム」と「エクスポート」のオプションが表示されます。 メインのコンテンツエリアには、「Word Document Processor」というタイトルと簡単な説明が表示されます:「Word文書を簡単にアップロードして処理できます。
では、文書をインポートしてみましょう。 画像では、「Honey research synopsis.docx」という名前のファイルを選択していることがわかります。 ファイル名は、「ファイルを選択」ボタンの代わりにアップロードエリアに表示されます。 この文書をアップロードし、処理する準備が整いました。
アップロードして処理」をクリックすると、アプリケーションがドキュメントを処理し、その内容を表示します。 ドキュメントの内容」セクションに、アップロードされたドキュメントの冒頭が表示されるようになりました。 タイトル「Beekeeping Technologies and Quality of Honey Production in Urban Areas(都市部における養蜂技術とハチミツ生産品質)」に続いてアブストラクトが表示されています。 これは、私たちのアプリケーションがWord文書のコンテンツを正常に読み取り、表示したことを示しています。
最後に、エクスポート機能をテストしてみましょう。 画像では、ナビゲーションバーの「エクスポート」ボタンをクリックすると、プロンプトが表示されます。 プロンプトでは、「ドキュメントの名前を入力してください」と求められます。(拡張子なし)申し訳ありませんが、翻訳するための具体的なテキストが提供されていません。翻訳するコンテンツを提供していただければ、日本語に翻訳いたします。 デフォルトの名前 "ExportedDocument "はあらかじめ入力されていますが、希望に応じて変更することができます。 このプロンプトでは、ダウンロードする前に、エクスポートしたドキュメントの名前をカスタマイズできます。
OK」をクリックすると、指定された名前の新しいWord文書が生成され、ダウンロード処理が開始されます。 このエクスポートされたドキュメントには、当社が処理したコンテンツや、アプリケーション内で行った修正が含まれています。
このプロセスを通じて、アプリケーションが意図したとおりに機能していることを確認できます。 このアプリケーションを使用して、Word文書のインポート、文書の作成、エクスポートを簡単に行うことができます。 ユーザーインターフェイスは、直感的で応答性に優れています。
結論として、私たちのWordDocumentProcessorアプリケーションは、Word文書処理をASP.NET Core Webアプリケーションに統合するパワーと柔軟性を実証することに成功しました。 IronWordライブラリを活用することで、Word文書を簡単にインポート、表示、エクスポートできる堅牢なソリューションを作成しました。 このアプリケーションは、より複雑な文書管理システムやレポートジェネレータのための強固な基盤として機能します。 IronWordの機能に興味のある開発者のために、ライブラリは以下のものを提供しています。無料試用. 試用期間終了後、ライセンスは$749から始まり、Webアプリケーションで高度なWordドキュメント処理機能を必要とする企業にとって経済的なソリューションとなります。
10 の .NET API 製品 オフィス文書用