跳至页脚内容
使用 IRONWORD

ASP .NET Core 导入和导出 Word 文件

本指南探讨了如何导入现有 Word 文档、显示其内容,以及如何使用 IronWord 库从头开始创建文档。 在本教程结束时,您将创建一个 ASP.NET Core Web 应用程序,它可以:

1.上传和阅读 Word 文档 2.在文本框中显示这些文档的内容 3.导出 Docx 文件

本项目非常适合需要将 Word 文档处理集成到其网络应用程序中的开发人员,无论是文档管理系统、报告生成器,还是任何其他涉及 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 项目

1.打开 Visual Studio 2019 或更高版本。

  1. 点击"创建新项目"。 3.搜索 "ASP.NET Core Web 应用程序 "并选择。 4.单击 "下一步"。 5.将您的项目命名为 "WordDocumentProcessor"(或任何您喜欢的名称)。 6.为您的项目选择 .NET Framework 和位置,然后单击 "创建"。

2.2 安装 IronWord NuGet 软件包

现在,我们已经建立了项目,让我们添加 IronWord 库:

1.右键单击解决方案资源管理器中的项目。 2.选择 "管理 NuGet 软件包"。 3.在 "浏览 "选项卡中,搜索 "IronWord"。 4.请查找 IronWord 官方软件包。 5.单击 "安装 "将其添加到您的项目中。

2.3 更新现有控制器和视图

让我们更新现有结构,加入文档处理功能:

1.我们将使用 Controllers 文件夹中现有的 HomeController.cs 文件处理逻辑。 2.我们将更新 Views/Home 文件夹中现有的 Index.cshtml 视图,以包含文档上传和显示功能。

现在,我们已经建立了项目并安装了 IronWord 软件包,可以开始实施文档导入和导出功能了。 我们将在 HomeController 中添加新方法,并修改索引视图以处理这些功能。 在下一节中,我们将重点利用现有的控制器和视图结构导入 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上传和处理方法

该方法负责处理文件的上传和处理:

[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 方法

该私人方法将提取的内容格式化为 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 代码负责处理文件上传过程,将文件发送到服务器进行处理,并用处理后的内容或错误信息更新用户界面。

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 文件,找到

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 文档的内容。

!a href="/static-assets/word/blog/asp-net-core-import-export-word/asp-net-core-import-export-word-5.webp">ASP .NET Core Import & Export A Word File: Figure 5

最后,让我们测试一下导出功能。 在图片中,我们可以看到当我们点击导航栏中的 "导出 "按钮时出现的提示。 提示要求我们 "输入文档名称(不含扩展名)"。 默认名称为 "ExportedDocument",但我们可以根据需要进行更改。 此提示允许我们在下载导出文档之前自定义其名称。

!a href="/static-assets/word/blog/asp-net-core-import-export-word/asp-net-core-import-export-word-6.webp">ASP .NET Core Import & Export A Word File: Figure 6

点击 "确定 "后,应用程序将以指定名称生成一个新的 Word 文档,并启动下载程序。 该导出文档包含我们处理过的内容或我们在应用程序中做过的任何修改。

ASP .NET Core 导入和导出一个 Word 文件:图 7

在整个过程中,我们可以看到应用程序按预期运行。 我们可以使用该应用程序轻松导入 Word 文档、创建文档和导出文档。 用户界面直观且反应灵敏。

结论

总之,我们的 WordDocumentProcessor 应用程序成功地展示了将 Word 文档处理集成到 ASP.NET Core 网络应用程序中的强大功能和灵活性。 通过利用 IronWord 库,我们创建了一个强大的解决方案,可以轻松导入、显示和导出 Word 文档。 该应用程序可作为更复杂的文档管理系统或报告生成器的坚实基础。 对于有兴趣探索 IronWord 功能的开发人员,该库提供 免费试用。 试用期结束后,许可证价格从 $799 开始,对于需要在其网络应用程序中使用高级 Word 文档处理功能的企业来说,这是一个经济高效的解决方案。

常见问题解答

如何在 ASP.NET Core 应用程序中导入 Word 文档?

您可以在 ASP.NET Core 应用程序中使用 IronWord 导入 Word 文档。它允许您在 UI 中提供上传区域,然后使用 IronWord 库处理文档,提取并在您的应用程序中显示其内容。

在 ASP.NET Core 中导出 Word 文档的步骤是什么?

要在 ASP.NET Core 中导出 Word 文档,请使用 IronWord 创建新文档,并为用户提供下载功能。您可以指定文件名,并使用 IronWord 的方法将内容写入 Word 文件。

我可以在 ASP.NET Core 应用程序中将 Word 文档转换为 PDF 吗?

是的,您可以使用 IronWord 在 ASP.NET Core 应用程序中将 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 处理集成到 Web 应用程序中的一些潜在用例是什么?

潜在用例包括文件管理系统和报告生成器,在这些系统中,通过使用 IronWord 集成 Word 处理功能,可以简化 Web 应用程序内的文档处理、编辑和转换过程。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。