IRONWORDの使用方法 ASP.NET Coreでワードファイルをインポート&エクスポートする Jordi Bardia 更新日:9月 18, 2025 Download IronWord NuGet Download Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article このガイドでは、既存のWordドキュメントをインポートし、その内容を表示し、IronWordライブラリを使用して初めからドキュメントを作成する方法を探ります。 このチュートリアルの終わりまでに、次のことができるASP.NET Coreウェブアプリケーションを作成します。 Wordドキュメントのアップロードと読み取り これらのドキュメントの内容をテキストボックスに表示 Docxファイルのエクスポート このプロジェクトは、ドキュメント管理システム、レポートジェネレーター、またはMicrosoft Wordファイルを含むその他のシナリオのいずれかにおいて、ウェブアプリケーションにWordドキュメント処理を統合する必要がある開発者に最適です。 前提条件 このチュートリアルを進めるには、次を持っているべきです: C#およびASP.NET Coreの基本知識 Visual Studio 2019以降がインストールされている(または、C#エクステンションを使用したVisual Studio Codeを使用できます) .NET Core SDK 3.1またはそれ以降 これらの技術に詳しくなくても心配しないでください - 我々はプロセスの各ステップを案内します! IronWordとは何ですか? IronWordは、開発者がプログラム的にMicrosoft Wordドキュメントを読み、操作し、作成できる.NETライブラリです。 高レベルのAPIを提供し、Wordファイルの作業を簡素化することで、プロジェクトに最適な選択肢となっています。 IronWordの主な機能には次のものがあります: 様々なWord形式(DOCX, DOCなど)の読み書き ドキュメントのコンテンツと構造の操作 テキストや段落のフォーマット テーブル、画像、およびその他のドキュメント要素の操作 ドキュメントのためのメールマージプロセス WordドキュメントをPDFドキュメントに簡単に変換し、最終的なWordドキュメントを簡単に共有可能なPDFファイルにする 我々が構築するものの概要と使用するツールを持ったので、プロジェクトの設定に入ることにしましょう! 2. プロジェクトの設定 このセクションでは、新しいASP.NET Coreプロジェクトを作成し、IronWordを使用するために必要なパッケージをインストールします。 2.1 新しいASP.NET Coreプロジェクトの作成 Visual Studio 2019以降を開きます。 「新しいプロジェクトの作成」をクリックします。 「ASP.NET Core Web Application」を検索して選択します。 「次へ」をクリックします。 プロジェクトに「WordDocumentProcessor」(またはお好みの名前)を名付けます。 .NETフレームワークとプロジェクトの場所を選択し、「作成」をクリックします。 2.2 IronWord NuGetパッケージのインストール プロジェクトがセットアップされたので、IronWordライブラリを追加しましょう。 ソリューションエクスプローラでプロジェクトを右クリックします。 「NuGetパッケージの管理」を選択します。 「ブラウズ」タブで「IronWord」を検索します。 公式のIronWordパッケージを探します。 「インストール」をクリックして、それをプロジェクトに追加します。 2.3 既存のコントローラとビューの更新 ドキュメント処理機能を組み込むために既存の構造を更新しましょう。 ドキュメント処理ロジックのために、Controllersフォルダの既存のHomeController.csを使用します。 ドキュメントのアップロードと表示機能を含むように、Views/Homeフォルダ内の既存のIndex.cshtmlビューを更新します。 これでプロジェクトがセットアップされ、IronWordパッケージがインストールされたので、ドキュメントのインポートとエクスポート機能の実装を開始する準備ができました。 HomeControllerに新しいメソッドを追加し、これらの機能を処理するためにIndexビューを変更します。 次のセクションでは、既存のコントローラとビューの構造を活用して、Wordドキュメントをインポートし、その内容を表示することに焦点を当てます。 3. Wordドキュメントのインポート このセクションでは、ASP.NET MVCアプリケーションでWordドキュメントをインポートして処理する機能の実装方法を探ります。 ユーザーインターフェースデザインとバックエンドコントローラロジックの両方をカバーします。 3.1 ユーザーインターフェースのデザイン Wordドキュメントをインポートするためのユーザーインターフェースは、直感的で視覚的に魅力的なように設計されています。 UIの主要なコンポーネントを分解してみましょう。 3.1.1 アップロードエリア アップロードエリアは、インターフェースの焦点であり、ユーザーに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> HTML このコードは、ファイルアイコン、隠しファイル入力、およびファイル選択ボタンとして機能するスタイル付きラベルを持つ視覚的に魅力的なアップロードエリアを作成します。 受け入れられるファイルタイプに関する情報と、アップロードと処理を開始するボタンも含まれています。 3.1.2 コンテンツ表示エリア ドキュメントの処理後、その内容は専用のエリアに表示されます。 <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> HTML このセクションは、処理されたドキュメントの内容を表示するためのスクロール可能なエリアを提供します。 3.2 コントローラ実装 HomeControllerは、Wordドキュメントのインポートと処理のためのサーバーサイドロジックを処理します。 主要なメソッドを見てみましょう。 3.2.1 UploadAndProcessメソッド このメソッドは、ファイルのアップロードと処理を担当します。 [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 OrElse 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 $vbLabelText $csharpLabel このメソッドは次のタスクを実行します。 アップロードされたファイルの形式が正しいか(DOCまたはDOCX)確認します。 IronWordライブラリを用いてドキュメントを処理します。 フォーマット済みの内容をJSONとして返します。 3.2.2 FormatContentAsHtmlメソッド このプライベートメソッドは抽出されたコンテンツを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 $vbLabelText $csharpLabel このメソッドは、各行を段落タグでラップし、空行を保持してドキュメントコンテンツを正しくHTMLとしてフォーマットすることを保証します。 3.3 クライアントサイドJavaScript ファイルのアップロードを処理し、処理されたコンテンツを表示するために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'; }); }); JAVASCRIPT このJavaScriptコードは、ファイルのアップロードプロセスを処理し、ファイルを処理のためにサーバーに送信し、UIを処理済みのコンテンツやエラーメッセージで更新します。 3.4 ユーザーインターフェースのスタイリング このアプリケーションは、ワープロとユーザーフレンドリーなインターフェースを作り出すためにカスタム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> このCSSは、ライトカラーの配色でクリーンでモダンなルックを作成します。 アップロードエリアには、白い背景と微妙な影の効果があり、コンテンツエリアはスクロール可能なデザインでライトグレーの背景を持っています。 ボーダー半径およびボックスシャドウのプロパティを使用して、インターフェイス要素に深みと視覚的な興味を追加します。 4. Wordドキュメントのエクスポート Word Document Processorをさらに強化して、ドキュメントをエクスポートできるようにしましょう。 この機能により、ユーザーはアプリケーションから新しいWordドキュメントを生成できます。 4.1 ユーザーインターフェースの更新 まず、ナビゲーションバーに「エクスポート」オプションを追加します。 Views/Sharedフォルダ内の_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> HTML アイコンにはFont Awesomeを使用しているので、セクションにCSSリンクを持っていることを確認してください。 このコードは、ナビゲーションバーに「エクスポート」リンクを追加します。 Font Awesomeをアイコン用に使用し、クリック時にexportDocument()関数を呼び出します。 リンクのデフォルトの動作を防ぐために、href="#"とreturn falseを使用しています。 4.2 クライアントサイドのエクスポートロジックの実装 次に、エクスポートプロセスを処理するJavaScript関数を追加しましょう。 _Layout.cshtmlファイルの下部、閉じるタグの前に次のスクリプトを追加します。 <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> HTML このJavaScript関数は、サーバーにWordドキュメントを作成するためのAJAX POSTリクエストを送信します。 成功時には、ユーザーにファイル名を尋ね、一時的なリンクを作成してファイルをダウンロードします。このリンクは自動的にクリックされ、DOMから削除されます。 どの段階でもエラーが発生した場合、アラートがユーザーに表示されます。 4.3 サーバーサイドのエクスポート機能の追加 次に、サーバーサイドのロジックを実装しましょう。 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 $vbLabelText $csharpLabel このメソッドは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 $vbLabelText $csharpLabel このメソッドは、ExportWordDocumentによって作成された一時ファイルを取得し、その内容をバイト配列に読み込み、その一時ファイルを削除します。提供されたユーザーファイル名またはデフォルト名が使用されます。 メソッドはその後、ダウンロード可能なWordドキュメントとしてファイルコンテンツを返します。 ファイルが見つからないかエラーが発生した場合、適切なHTTPレスポンスが返されます。 4.4 アプリケーションのビジュアルデザインの強化 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> このCSSブロックは、アプリケーションのカラースキームとレイアウトを定義します。 CSS変数(カスタムプロパティ)を使用してアプリ全体の一貫したカラーパレットを作成しています。スタイルは、ボディ、ナビバー、フッターなどのさまざまな要素をターゲットにし、一貫性のあるデザインを保証します。 ホバー効果やアイコンの統合を特徴とする、クリーンでモダンな外観のナビバーを設定しました。 現在のアプリケーションはWordドキュメントに焦点を当てていますが、IronPDFを使用してPDFドキュメントに対応を含むようにサポートを拡張し、より広範囲のファイルタイプをカバーするために機能を拡張できます。システムは、ユーザーが現在のWord形式オプションに加えて自分のドキュメントをPDFファイルとしてエクスポートすることを可能にするように拡張することができます。 5. アプリケーションの実行 私たちのWordDocumentProcessorアプリケーションを実行することから始めましょう。 画像で見ることができるように、ブラウザに正常にアプリケーションが読み込まれました。 インターフェースはクリーンでユーザーフレンドリーで、トップには「Home」と「Export」オプションを表示するナビゲーションバーがあります。 メインコンテンツエリアには「Word Document Processor」というタイトルと、簡単な説明:「Wordドキュメントを簡単にアップロードして処理」と表示されています。 さて、ドキュメントをインポートしてみましょう。 画像で見えるように、「Honey research synopsis.docx」ファイルを選択しました。 ファイル名は「ファイルを選択」ボタンを置き換えてアップロードエリアに表示されます。 このドキュメントをアップロードして処理する準備ができました。 「アップロードして処理」をクリックすると、アプリケーションがドキュメントを処理し、その内容を表示します。 「ドキュメントコンテンツ」セクションには、アップロードされたドキュメントの冒頭が表示されます。 「Beekeeping Technologies and Quality of Honey Production in Urban Areas」というタイトルとともに、抽象が続いています。 これにより、我々のアプリケーションがWordドキュメントの内容を正常に読み取って表示したことが実証されます。 最後に、エクスポート機能をテストしてみましょう。 画像で、ナビゲーションバーの「エクスポート」ボタンをクリックしたときに表示されるプロンプトが見えます。 プロンプトは、「ドキュメント名を入力してください(拡張子なし)」と尋ねます。 デフォルトの名前「ExportedDocument」は事前に入力されていますが、必要に応じて変更できます。 このプロンプトにより、ダウンロード前にエクスポートされたドキュメントの名前をカスタマイズすることができます。 「OK」をクリックすると、アプリケーションは新しいWordドキュメントを指定した名前で生成し、ダウンロードプロセスを開始します。 このエクスポートされたドキュメントには、アプリケーション内で処理したコンテンツまたは変更を加えた内容が含まれています。 このプロセス全体を通じて、アプリケーションが意図した通りに機能しているのがわかります。 このアプリケーションを使用して、Wordドキュメントをインポートしたり、ドキュメントを作成したり、簡単にエクスポートしたりできます。 ユーザーインターフェイスは直感的で応答性があります。 結論 結論として、私たちのWordDocumentProcessorアプリケーションは、ASP.NET CoreウェブアプリケーションにWordドキュメント処理を統合する力と柔軟性を実証しています。 IronWordライブラリを活用することで、Wordドキュメントのインポート、表示、エクスポートを簡単に行うための強力なソリューションを作成しました。 このアプリケーションは、より複雑なドキュメント管理システムまたはレポートジェネレーターの堅実な基盤を提供します。 IronWordsの機能を探求したい開発者向けに、このライブラリは無料トライアルを提供しています。 トライアル後のライセンス料金は$799から始まり、ウェブアプリケーションで高度なWordドキュメント処理機能を必要とする企業にとっては費用効果の高いソリューションです。 よくある質問 ASP.NET Core アプリケーションで Word ドキュメントをインポートするにはどうすればよいですか? ASP.NET Core アプリケーションで Word ドキュメントをインポートするには、IronWord を使用します。UI でアップロードエリアを提供し、IronWord ライブラリを使用してドキュメントを処理し、アプリケーション内でその内容を抽出して表示できます。 ASP.NET Core で Word ドキュメントをエクスポートする手順は何ですか? ASP.NET Core で Word ドキュメントをエクスポートするには、IronWord を使用して新しいドキュメントを作成し、ユーザーがそれをダウンロードする機能を提供します。ファイル名を指定し、IronWord のメソッドを使用して Word ファイルにコンテンツを書き込むことができます。 ASP.NET Core アプリケーションで Word ドキュメントを PDF に変換できますか? はい、ASP.NET Core アプリケーションで IronWord を使用して Word ドキュメントを PDF に変換できます。IronWord は、Word ドキュメントをPDF形式に変換する方法を提供しており、共有やアクセスしやすさを向上させます。 アプリケーションは、どのファイル形式を Word ドキュメントのインポートにサポートしていますか? アプリケーションは、IronWord ライブラリを使用して .DOC や .DOCX のファイル形式のインポートをサポートしており、これらのドキュメントを ASP.NET Core アプリケーション内で処理および表示できます。 ドキュメント処理アプリケーションの強化に JavaScript はどのように使用されていますか? JavaScript は、ファイルアップロードを処理し、IronWord でのドキュメント処理のためにサーバーに AJAX リクエストを送信し、処理されたコンテンツやエラーメッセージでユーザーインターフェースを更新し、シームレスなユーザー体験を確保します。 ASP.NET Core で Word 処理アプリを開発するための前提条件は何ですか? ASP.NET Core で Word 処理アプリを開発するには、C# および ASP.NET Core の基本的な知識が必要で、Visual Studio 2019 以降、または C# 拡張機能付きの Visual Studio Code、および .NET Core SDK 3.1 以上がインストールされている必要があります。 ドキュメント処理により良いユーザーインターフェースを設計するにはどうすればよいですか? ユーザーインターフェースは、Word ドキュメントを選択するためのアップロード領域と、処理されたコンテンツを表示するためのコンテンツ表示エリアで設計できます。カスタム CSS を使用してデザインを向上させ、魅力的でユーザーフレンドリーな体験を提供します。 ウェブアプリケーションで Word 処理を統合する潜在的なユースケースは? 潜在的なユースケースには、ドキュメント管理システムやレポートジェネレーターが含まれ、IronWord を利用した Word 処理機能を統合することで、ウェブアプリケーション内でのドキュメント処理、編集、変換プロセスを効率化できます。 Jordi Bardia 今すぐエンジニアリングチームとチャット ソフトウェアエンジニア Jordiは、最も得意な言語がPython、C#、C++であり、Iron Softwareでそのスキルを発揮していない時は、ゲームプログラミングをしています。製品テスト、製品開発、研究の責任を分担し、Jordiは継続的な製品改善において多大な価値を追加しています。この多様な経験は彼を挑戦させ続け、興味を持たせており、Iron Softwareで働くことの好きな側面の一つだと言います。Jordiはフロリダ州マイアミで育ち、フロリダ大学でコンピュータサイエンスと統計学を学びました。 関連する記事 更新日 7月 28, 2025 VS 2022 プログラムで新しいワード文書を作成する(チュートリアル) 今日のチュートリアルでは、IronWordを使用してMicrosoft Word文書をプログラムで作成する方法を簡単に説明し、簡単な例を提供します。 詳しく読む 更新日 6月 22, 2025 C#を使用してワードでテキストを整列する方法 IronWord NuGetパッケージに深く掘り下げ、このパッケージを使用してテキストや段落を整列する方法を探ります。 詳しく読む 更新日 6月 22, 2025 C#でワードテンプレートを使用してワード文書を生成する方法 この記事では、IronWordを使用してワード文書テンプレートを埋める方法を説明し、このプロセスを実演するための実践的な例を提供します。 詳しく読む VS 2022 プログラムで新しい...
更新日 7月 28, 2025 VS 2022 プログラムで新しいワード文書を作成する(チュートリアル) 今日のチュートリアルでは、IronWordを使用してMicrosoft Word文書をプログラムで作成する方法を簡単に説明し、簡単な例を提供します。 詳しく読む
更新日 6月 22, 2025 C#を使用してワードでテキストを整列する方法 IronWord NuGetパッケージに深く掘り下げ、このパッケージを使用してテキストや段落を整列する方法を探ります。 詳しく読む
更新日 6月 22, 2025 C#でワードテンプレートを使用してワード文書を生成する方法 この記事では、IronWordを使用してワード文書テンプレートを埋める方法を説明し、このプロセスを実演するための実践的な例を提供します。 詳しく読む