使用 IRONWORD ASP .NET Core 匯入和匯出 Word 檔案 Jordi Bardia 更新:9月 18, 2025 下載 IronWord NuGet 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 本指南探討如何匯入現有的 Word 文件、顯示其內容以及使用IronWord 庫從頭開始建立文件。 完成本教學後,您將建立一個能夠執行以下操作的ASP.NET Core Web 應用程式: 上傳和閱讀 Word 文件 將這些文件的內容顯示在文字方塊中 匯出 Docx 文件 對於需要將 Word 文件處理整合到其 Web 應用程式中的開發人員來說,無論是文件管理系統、報表產生器,或是任何其他涉及 Microsoft Word 文件的場景,本專案都是完美的。 先決條件 要學習本教程,您應該具備以下條件: 具備 C# 和 ASP.NET Core 的基礎知識 已安裝 Visual Studio 2019 或更高版本(或者,您可以使用帶有 C# 擴充功能的 Visual Studio Code) .NET Core SDK 3.1 或更高版本 即使您不熟悉這些技術也不用擔心—我們將引導您完成整個過程的每一步! IronWord是什麼? IronWord是一個 .NET 程式庫,允許開發人員以程式設計方式讀取、操作和建立 Microsoft Word 文件。 它提供了一個高級 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 應用程式"並選擇它。 點選"下一步"。 將你的專案命名為"WordDocumentProcessor"(或你喜歡的任何名稱)。 選擇 .NET Framework 和專案位置,然後按一下"建立"。 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 文件的使用者介面設計直覺且美觀。 讓我們來分解一下使用者介面的關鍵組成部分: 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 庫處理文件。 3.以 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 程式碼採用淺色調方案,營造出簡潔現代的外觀。 上傳區域採用白色背景,並帶有微妙的陰影效果,而內容區域則採用可捲動設計,背景為淺灰色。 使用 border-radius 和 box-shadow 屬性可以為介面元素增加深度和視覺趣味性。 4. 匯出 Word 文件 為了不斷改進我們的 Word 文件處理器,讓我們加入匯出文件的功能。 此功能將允許使用者透過我們的應用程式產生新的 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="#"並回傳 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 函數會向伺服器發送 AJAX POST 請求以建立 Word 文件。 成功後,程式會提示使用者輸入檔名,然後建立一個臨時連結供使用者下載檔案。該連結會自動點擊,之後從 DOM 移除。 如果在任何階段出現錯誤,都會向使用者顯示警報。 4.3 新增伺服器端導出功能 現在,讓我們來實作伺服器端邏輯。 打開 Controllers 資料夾中的 HomeController.cs 檔案。 我們將新增兩種方法來處理匯出過程。 首先,我們來新增建立 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 文件處理器的整體外觀和體驗,我們直接在 _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 應用程式。 如圖所示,該應用程式已在瀏覽器中成功載入。 介面簡潔友好,頂部導覽列顯示"首頁"和"匯出"選項。 主內容區域顯示標題"Word 文件處理器"和簡短描述:"輕鬆上傳和處理您的 Word 文件。" ASP.NET Core 匯入和匯出 Word 檔案:圖 3 現在,我們來嘗試導入一個文件。 從圖中我們可以看到,我們選擇了一個名為"Honey research synopsis.docx"的檔案。 檔案名稱將顯示在上傳區域,取代"選擇檔案"按鈕。 我們現在可以上傳並處理這份文件了。 ASP.NET Core 匯入和匯出 Word 檔案:圖 4 點擊"上傳並處理"後,應用程式將處理文件並顯示其內容。 "文檔內容"部分現在顯示已上傳文件的開頭部分。 我們可以看到標題"城市地區養蜂技術和蜂蜜生產品質",後面跟著摘要。 這證明我們的應用程式已成功讀取並顯示了 Word 文件的內容。 ASP.NET Core 匯入和匯出 Word 檔案:圖 5 最後,我們來測試一下匯出功能。 如圖所示,點擊導覽列中的"匯出"按鈕時會出現一個提示。 提示要求我們"輸入文件名稱(不含副檔名)"。 預設名稱"ExportedDocument"已預先填寫,但我們可以根據需要更改此名稱。 此提示允許我們在下載匯出文件之前自訂其名稱。 ASP.NET Core 匯入和匯出 Word 檔案:圖 6 點擊"確定"後,應用程式將產生一個指定名稱的新 Word 文檔,並開始下載過程。 此匯出文件包含我們已處理的內容或我們在應用程式中所做的任何修改。 ASP.NET Core 匯入和匯出 Word 檔案:圖 7 在此過程中,我們可以看到該應用程式運作正常。 我們可以使用此應用程式輕鬆匯入 Word 文件、建立文件和匯出文件。 使用者介面直覺且反應迅速。 結論 總而言之,我們的 WordDocumentProcessor 應用程式成功地展示了將 Word 文件處理整合到 ASP.NET Core Web 應用程式中的強大功能和靈活性。 透過利用 IronWord 庫,我們創建了一個強大的解決方案,可以輕鬆地匯入、顯示和匯出 Word 文件。 該應用程式為更複雜的文件管理系統或報表產生器奠定了堅實的基礎。 對於有興趣探索 IronWords 功能的開發者,此程式庫提供免費試用。 試用期結束後,授權費用從$799起,對於需要在 Web 應用程式中使用高級 Word 文件處理功能的企業來說,這是一個經濟高效的解決方案。 常見問題解答 如何在 ASP.NET Core 應用程式中匯入 Word 文件? 您可以使用 IronWord for .NET 在 ASP.NET Core 應用程式中匯入 Word 文件。它允許您在 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 library 匯入 .DOC 和 .DOCX 檔案格式,讓您可以在 ASP.NET Core 應用程式中處理和顯示這些文件。 JavaScript 如何用於增強文件處理應用程式? JavaScript 用於處理檔案上傳、傳送 AJAX 請求至伺服器以便使用 IronWord 處理文件,並將處理過的內容或錯誤訊息更新至使用者介面,以確保使用者體驗順暢無礙。 在 ASP.NET Core 中開發文書處理應用程式的先決條件是什麼? 要在 ASP.NET Core 中開發文字處理應用程式,您需要具備 C# 和 ASP.NET Core 的基本知識、Visual Studio 2019 或更新版本,或具備 C# 延伸功能的 Visual Studio Code,以及安裝 .NET Core SDK 3.1 或更新版本。 如何設計使用者介面以便更好地處理文件? 使用者介面可設計為上傳區域以選擇 Word 文件,以及顯示已處理內容的內容顯示區域。可使用自訂 CSS 來強化設計,以提供具吸引力的使用者友善體驗。 在 Web 應用程式中整合 Word 處理的潛在用例有哪些? 潛在用例包括文件管理系統和報表產生器,使用 IronWord 整合 Word 處理功能可以簡化 Web 應用程式內的文件處理、編輯和轉換流程。 Jordi Bardia 立即與工程團隊聊天 軟體工程師 Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。 相關文章 更新7月 28, 2025 VS 2022 程式化建立新 Word 文件 (教學) 在今天的教程中,我將簡單介紹如何使用 IronWord 程式化地建立 Microsoft Word 文件,並提供簡單的範例。 閱讀更多 更新6月 22, 2025 如何使用 C# 在 Word 中對齊文字 讓我們深入瞭解 IronWord NuGet 套件,以及如何使用此套件對齊文字或段落 閱讀更多 更新6月 22, 2025 如何在 C# 中使用 Word 模板生成 Word 文檔 在這篇文章中,我們將介紹如何使用 IronWord 來填充 Word 文件範本,並提供一個實例來說明這個過程。 閱讀更多 VS 2022 程式化建立新 Word 文...
更新7月 28, 2025 VS 2022 程式化建立新 Word 文件 (教學) 在今天的教程中,我將簡單介紹如何使用 IronWord 程式化地建立 Microsoft Word 文件,並提供簡單的範例。 閱讀更多
更新6月 22, 2025 如何在 C# 中使用 Word 模板生成 Word 文檔 在這篇文章中,我們將介紹如何使用 IronWord 來填充 Word 文件範本,並提供一個實例來說明這個過程。 閱讀更多