跳至頁尾內容
USING IRONWORD

VS 2022 程式化建立新 Word 文件(教程)

本指南探討如何匯入現有Word文件、顯示其內容,並使用IronWord程式庫從頭建立文件。 在本教程結束時,您將建立一個ASP.NET Core網頁應用程式,可以:

  1. 上傳和讀取Word文件
  2. 在文字框中顯示這些文件的內容
  3. 匯出Docx文件

此專案非常適合需要將Word文件處理整合到其網頁應用程式中的開發者,無論是文件管理系統、報告生成器,還是任何涉及Microsoft Word文件的情境。

先決條件

要跟隨本教程,您應該具備:

  • 基本的C#和ASP.NET Core知識
  • 安裝了Visual Studio 2019或更高版本(您也可以使用Visual Studio Code與C#擴展)
  • .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專案

  1. 啟動Visual Studio 2019或更高版本。
  2. 點擊"建立新專案"。
  3. 搜索"ASP.NET Core Web Application"並選擇它。
  4. 點擊"下一步"。
  5. 將您的專案命名為"WordDocumentProcessor"(或者您喜歡的其他名稱)。
  6. 選擇.NET Framework的版本及專案的位置,然後點擊"建立"。

2.2 安裝IronWord NuGet套件

現在我們已經設置了專案,讓我們新增IronWord程式庫:

  1. 右鍵點擊在解決方案總管中的專案。
  2. 選擇"管理NuGet套件"。
  3. 在"瀏覽"標籤中搜索"IronWord"。
  4. 尋找官方IronWord套件。
  5. 點擊"安裝"以將其新增到您的專案中。

2.3 更新現有的控制器和視圖

讓我們更新現有結構以合併文件處理功能:

  1. 我們將使用控制器資料夾中的現有HomeController.cs作為文件處理邏輯。
  2. 我們將更新視圖/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

此方法執行以下任務:

  1. 驗證上傳的文件,確保其在正確的文件格式(DOC或DOCX)。
  2. 使用IronWord程式庫處理文件。
  3. 以JSON格式返回格式化的內容。

3.2.2 FormatContentAsHtml Method

此私有方法將提取的內容格式化為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文件,找到

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 增加伺服器端匯出功能

現在,讓我們實現伺服器端邏輯。 打開控制器資料夾中的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 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變數(自定義屬性)在整個應用程式中創造一致的色彩調色板。樣式針對多個元素,包括body、navbar和footer,確保設計的一致性。 我們設計了一個乾淨、現代的導航欄,具有懸停效果和圖標整合功能。

雖然我們的應用程式當前重點在Word文件,但我們可以使用IronPDF來包含對PDF文件的支援,擴展功能以涵蓋更廣泛的文件型別。該系統可以擴展,允許使用者將他們的文件除了目前的Word格式外,還可以匯出為PDF文件。

5. 運行應用程式

讓我們從運行我們的WordDocumentProcessor應用程式開始。 如圖片所示,應用程式已成功在瀏覽器中載入。 使用者介面乾淨且友好,頂部導航欄顯示"首頁"和"匯出"選項。 主要內容區域顯示"Word Document Processor"標題及簡短說明:"輕鬆上傳和處理您的Word文件。"

ASP .NET Core Import & Export A Word File: Figure 3

現在,讓我們嘗試匯入一個文件。 在圖片中,我們可以看到我們選擇了一個名為"Honey research synopsis.docx"的文件。 文件名顯示在上傳區域中,取代了"選擇文件"按鈕。 我們現在準備上傳並處理此文件。

ASP .NET Core Import & Export A Word File: Figure 4

點擊"上傳和處理"後,應用程式處理文件並顯示其內容。 "文件內容"部分現在顯示上傳文件的開頭。 我們可以看到標題"Beekeeping Technologies and Quality of Honey Production in Urban Areas"接著是一個摘要。 這表明我們的應用程式已成功讀取並顯示Word文件的內容。

ASP .NET Core Import & Export A Word File: Figure 5

最後,讓我們測試匯出功能。 在圖片中,我們看到當我們點擊導航欄中的"匯出"按鈕時出現提示。 提示詢問我們"輸入文件的名稱(不含擴展名)"。 預設名稱"ExportedDocument"已預填,但如果我們願意,我們可以更改。 此提示讓我們能夠在下載前自定義匯出文件的名稱。

ASP .NET Core Import & Export A Word File: Figure 6

點擊"確定"後,應用程式使用指定的名稱生成新的Word文件並啟動下載過程。 此匯出文件包含我們已處理的內容或我們在應用程式內進行的任何修改。

ASP .NET Core Import & Export A Word File: Figure 7

在此過程中,我們可以看到應用程式按預期運行。 我們可以使用此應用程式來匯入Word文件,建立文件並輕鬆匯出它們。 使用者介面直觀且具響應性。

結論

總之,我們的WordDocumentProcessor應用程式成功展示了將Word文件處理整合到ASP.NET Core網頁應用程式中的功能和靈活性。 藉由利用IronWord程式庫,我們建立了一個強大的解決方案,能夠輕鬆地匯入、顯示和匯出Word文件。 此應用程式是構建更複雜的文件管理系統或報告生成器的穩固基礎。 對於有興趣探索IronWord功能的開發者,該程式庫提供試用授權。 試用期過後,授權起價在$999,這對於需要在其網頁應用程式中進行高級Word文件處理的企業來說是一個具有成本效益的解決方案。

常見問題

我如何在 ASP.NET Core 應用中匯入 Word 文件?

您可以使用 IronWord 在 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 程式庫匯入 .DOC 和 .DOCX 文件格式,允許您在 ASP.NET Core 應用程式中處理和顯示這些文件。

JavaScript 如何用於增強文件處理應用程式?

JavaScript 用於處理文件上傳,發送 AJAX 請求到伺服器以使用 IronWord 處理文件,並更新使用者介面的處理內容或錯誤訊息,確保流暢的使用者體驗。

開發 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 處理能力,可以簡化網頁應用中的文件處理、編輯和轉換過程。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話