Przejdź do treści stopki
UZYWANIE IRONWORD

ASP .NET Core importuj i eksportuj plik Word

W tym przewodniku omówiono, jak importować istniejące dokumenty WORD, wyświetlać ich zawartość oraz tworzyć dokumenty od podstaw przy użyciu biblioteki IronWord. Pod koniec tego samouczka stworzysz aplikację internetową ASP.NET Core, która będzie potrafiła:

  1. Prześlij i przeczytaj dokumenty WORD
  2. Wyświetl zawartość tych dokumentów w polu tekstowym
  3. Wyeksportuj plik Docx

Ten projekt jest idealny dla programistów, którzy muszą zintegrować przetwarzanie dokumentów WORD ze swoimi aplikacjami internetowymi, czy to w systemach zarządzania dokumentami, generatorach raportów, czy w jakimkolwiek innym scenariuszu z wykorzystaniem plików Microsoft WORD.

Wymagania wstępne

Aby śledzić ten samouczek, należy posiadać:

  • Podstawowa znajomość języka C# i platformy ASP.NET Core
  • Zainstalowany program Visual Studio 2019 lub nowszy (alternatywnie można użyć programu Visual Studio Code z rozszerzeniem C#)
  • .NET Core SDK 3.1 lub nowszy

Nie martw się, jeśli nie jesteś ekspertem w tych technologiach – poprowadzimy Cię przez każdy etap procesu!

Czym jest IronWord?

IronWord to biblioteka .NET, która pozwala programistom programowo odczytywać, modyfikować i tworzyć dokumenty Microsoft Word. Zapewnia API wysokiego poziomu, które upraszcza pracę z plikami WORD, co czyni go doskonałym wyborem dla naszego projektu.

Niektóre kluczowe funkcje IronWord to:

  • Odczytywanie i zapisywanie różnych formatów WORDa (DOCX, DOC itp.)
  • Manipulowanie treścią i strukturą dokumentu
  • Formatowanie tekstu i akapitów
  • Praca z tabelami, obrazami i innymi elementami dokumentu
  • Proces korespondencji seryjnej dla dokumentów
  • Łatwa konwersja dokumentu WORDa do formatu PDF, umożliwiająca przekształcenie gotowych dokumentów WORDa w pliki PDF, które można łatwo udostępniać

Teraz, gdy mamy już ogólny zarys tego, co tworzymy, oraz narzędzi, których będziemy używać, przejdźmy do konfiguracji naszego projektu!

2. Konfiguracja projektu

W tej sekcji utworzymy nowy projekt ASP.NET Core i zainstalujemy pakiety niezbędne do pracy z IronWord.

2.1 Tworzenie nowego projektu ASP.NET Core

  1. Otwórz program Visual Studio 2019 lub nowszą wersję.
  2. Click on "Create a new project".
  3. Wyszukaj "Aplikacja internetowa ASP.NET Core" i wybierz ją.
  4. Kliknij "Dalej".
  5. Nazwij swój projekt "WordDocumentProcessor" (lub dowolną inną nazwą).
  6. Wybierz platformę .NET Framework oraz lokalizację dla swojego projektu, a następnie kliknij "Utwórz".

2.2 Instalacja pakietu IronWord NuGet

Skoro mamy już skonfigurowany projekt, dodajmy bibliotekę IronWord:

  1. Right-click on your project in the Solution Explorer.
  2. Wybierz opcję "Zarządzaj pakietami NuGet".
  3. W zakładce "Przeglądaj" wyszukaj "IronWord".
  4. Poszukaj oficjalnego pakietu IronWord.
  5. Kliknij "Zainstaluj", aby dodać ją do swojego projektu.

2.3 Aktualizacja istniejącego kontrolera i widoku

Zaktualizujmy naszą istniejącą strukturę, aby uwzględnić funkcjonalność przetwarzania dokumentów:

  1. Do logiki przetwarzania dokumentów wykorzystamy istniejący plik HomeController.cs znajdujący się w folderze Controllers.
  2. Zaktualizujemy istniejący widok Index.cshtml w folderze Views/Home, aby uwzględnić funkcję przesyłania i wyświetlania dokumentów.

Teraz, gdy mamy już skonfigurowany projekt i zainstalowany pakiet IronWord, jesteśmy gotowi do rozpoczęcia wdrażania funkcji importu i eksportu dokumentów. Dodamy nowe metody do naszego HomeController i zmodyfikujemy widok Index, aby obsługiwał te funkcje. W następnej sekcji skupimy się na importowaniu dokumentów WORDa i wyświetlaniu ich treści, wykorzystując naszą istniejącą strukturę kontrolerów i widoków.

3. Importowanie dokumentów WORD

W tej sekcji omówimy, jak zaimplementować funkcję importowania i przetwarzania dokumentów WORD w aplikacji ASP.NET MVC. Omówimy zarówno projekt interfejsu użytkownika, jak i logikę kontrolera zaplecza.

3.1 Projektowanie interfejsu użytkownika

Interfejs użytkownika służący do importowania dokumentów WORD został zaprojektowany tak, aby był intuicyjny i atrakcyjny wizualnie. Przeanalizujmy kluczowe elementy interfejsu użytkownika:

3.1.1 Obszar przesyłania plików

Obszar przesyłania plików jest centralnym punktem interfejsu, zachęcającym użytkowników do wybierania i przesyłania dokumentów WORD. Oto jak wygląda struktura tekstu:

<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

Ten kod tworzy atrakcyjny wizualnie obszar przesyłania plików z ikoną pliku, ukrytym polem wprowadzania pliku oraz stylizowaną etykietą pełniącą rolę przycisku wyboru pliku. Zawiera również informacje o akceptowanych typach plików oraz przycisk do rozpoczęcia przesyłania i przetwarzania.

3.1.2 Obszar wyświetlania treści

Po przetworzeniu dokumentu jego treść jest wyświetlana w specjalnym obszarze:

<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

Ta sekcja zawiera obszar przewijalny, w którym wyświetlana jest przetworzona treść dokumentu.

3.2 Implementacja kontrolera

HomeController obsługuje logikę po stronie serwera dotyczącą importowania i przetwarzania dokumentów WORD. Przyjrzyjmy się kluczowym metodom:

3.2.1 Metoda UploadAndProcess

Ta metoda odpowiada za obsługę przesyłania i przetwarzania plików:

[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

Ta metoda wykonuje następujące zadania:

  1. Sprawdza przesłany plik, upewniając się, że ma on prawidłowy format (DOC lub DOCX).
  2. Przetwarza dokument przy użyciu biblioteki IronWord.
  3. Zwraca sformatowaną treść w formacie JSON.

3.2.2 Metoda FormatContentAsHtml

Ta metoda prywatna formatuje wyodrębnioną treść do postaci 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

Ta metoda zapewnia, że treść dokumentu jest poprawnie sformatowana jako HTML, z każdą linią zawartą w tagach akapitu i zachowanymi pustymi liniami.

3.3 JavaScript po stronie klienta

Aby obsłużyć przesyłanie plików i wyświetlić przetworzoną treść, używamy 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

Ten kod JavaScript obsługuje proces przesyłania plików, wysyła plik do serwera w celu przetworzenia oraz aktualizuje interfejs użytkownika o przetworzoną treść lub komunikaty o błędach.

3.4 Stylizacja interfejsu użytkownika

Aplikacja wykorzystuje niestandardowy CSS do tworzenia atrakcyjnego i przyjaznego dla użytkownika interfejsu.

<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>

Ten CSS tworzy przejrzysty, nowoczesny wygląd z jasną kolorystyką. Obszar przesyłania plików ma białe tło z subtelnymi efektami cieni, natomiast obszar treści ma układ umożliwiający przewijanie na jasnoszarym tle. Zastosowanie właściwości border-radius i box-shadow nadaje elementom interfejsu głębię i atrakcyjny wygląd.

4. Exporting Word Documents

As we continue to enhance our Word Document Processor, let's add the ability to export documents. This feature will allow users to generate a new Word document from our application.

4.1 Updating the User Interface

First, we'll add an "Export" option to our navigation bar. Open the _Layout.cshtml file in the Views/Shared folder and locate the

4.2 Implementing Client-Side Export Logic

Now, let's add the JavaScript function that will handle the export process. At the bottom of our _Layout.cshtml file, just before the closing tag, we'll add the following script:

<script>
function exportDocument() {
    $.ajax({
        url: '/Home/ExportWordDocument',
        type: 'POST',
        success: function (response) {
            if (response.success) {
                var fileName = prompt("Enter a name for the document (without extension):", "ExportedDocument");
                if (fileName === null) {
                    return;
                }
                fileName = (fileName.trim() || "ExportedDocument").replace(/\.[^/.]+$/, "") + ".docx";
                var a = document.createElement('a');
                a.style.display = 'none';
                a.href = '/Home/DownloadFile?tempFilePath=' + encodeURIComponent(response.tempFilePath) + '&userFileName=' + encodeURIComponent(fileName);
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            } else {
                alert('Failed to export document: ' + response.message);
            }
        },
        error: function () {
            alert('An error occurred while exporting the document.');
        }
    });
}
</script>
<script>
function exportDocument() {
    $.ajax({
        url: '/Home/ExportWordDocument',
        type: 'POST',
        success: function (response) {
            if (response.success) {
                var fileName = prompt("Enter a name for the document (without extension):", "ExportedDocument");
                if (fileName === null) {
                    return;
                }
                fileName = (fileName.trim() || "ExportedDocument").replace(/\.[^/.]+$/, "") + ".docx";
                var a = document.createElement('a');
                a.style.display = 'none';
                a.href = '/Home/DownloadFile?tempFilePath=' + encodeURIComponent(response.tempFilePath) + '&userFileName=' + encodeURIComponent(fileName);
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            } else {
                alert('Failed to export document: ' + response.message);
            }
        },
        error: function () {
            alert('An error occurred while exporting the document.');
        }
    });
}
</script>
HTML

This JavaScript function sends an AJAX POST request to the server to create a Word document. On success, it prompts the user for a file name and then creates a temporary link to download the file. The link is automatically clicked and then removed from the DOM. If there's an error at any stage, an alert is shown to the user.

4.3 Adding Server-Side Export Functionality

Now, let's implement the server-side logic. Open the HomeController.cs file in the Controllers folder. We'll add two new methods to handle the export process.

First, let's add the method to create the Word 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 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

This method creates a new Word document using the IronWord library, adds some test text, and saves it to a temporary file with a unique name. It returns a JSON object with the success status and the path to the temporary file. If an error occurs, it logs the exception and returns a failure message.

Next, let's add the method to handle the file download:

[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

This method retrieves the temporary file created by ExportWordDocument, reads its contents into a byte array, and then deletes the temporary file. It uses the provided user filename or a default name if none is provided. The method then returns the file content as a downloadable Word document. If the file is not found or an error occurs, appropriate HTTP responses are returned.

4.4 Enhancing the Application's Visual Design

To improve the overall look and feel of our Word Document Processor, we've added custom CSS directly in the _Layout.cshtml file. Let's examine the styling we've implemented:

<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>

This CSS block defines our application's color scheme and layout. We're using CSS variables (custom properties) to create a consistent color palette throughout the app. The styles target various elements including the body, navbar, and footer, ensuring a cohesive design. We've set up the navbar with a clean, modern look, featuring hover effects and icon integration.

While our application currently focuses on Word documents, we can use IronPDF to include support for PDF documents and expand its functionality to cover a wider range of file types. The system could be extended to allow users to export their documents as a PDF file in addition to the current Word format options.

5. Running the Application

Let's start by running our WordDocumentProcessor application. As we can see in the image, the application has loaded successfully in the browser. The interface is clean and user-friendly, with a navigation bar at the top showing "Home" and "Export" options. The main content area displays the title "Word Document Processor" and a brief description: "Upload and process your Word documents with ease."

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

Now, let's try importing a document. In the image, we can see that we've selected a file named "Honey research synopsis.docx". The file name is displayed in the upload area, replacing the "Choose File" button. We're now ready to upload and process this document.

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

After clicking "Upload and Process", the application processes the document and displays its content. The "Document Content" section now shows the beginning of the uploaded document. We can see the title "Beekeeping Technologies and Quality of Honey Production in Urban Areas" followed by an abstract. This demonstrates that our application has successfully read and displayed the content of the Word document.

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

Finally, let's test the export functionality. In the image, we see a prompt that appears when we click the "Export" button in the navigation bar. The prompt asks us to "Enter a name for the document (without extension)". The default name "ExportedDocument" is pre-filled, but we can change this if we wish. This prompt allows us to customize the name of our exported document before downloading it.

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

After clicking "OK", the application generates a new Word document with the specified name and initiates the download process. This exported document contains the content we've processed or any modifications we've made within the application.

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

Throughout this process, we can see that the application is functioning as intended. We can use this application for importing Word documents, creating documents, and exporting them with ease. The user interface is intuitive and responsive.

Wnioski

In conclusion, our WordDocumentProcessor application successfully demonstrates the power and flexibility of integrating Word document processing into an ASP.NET Core web application. By leveraging the IronWord library, we've created a robust solution for importing, displaying, and exporting Word documents with ease. This application serves as a solid foundation for more complex document management systems or report generators. For developers interested in exploring IronWords's capabilities, the library offers a free trial. After the trial, licensing starts at $799, making it a cost-effective solution for businesses requiring advanced Word document processing functionality in their web applications.

Często Zadawane Pytania

Jak mogę zaimportować dokumenty Word w aplikacji ASP.NET Core?

Możesz zaimportować dokumenty Word w aplikacji ASP.NET Core, używając IronWord. Umożliwia to dostarczenie obszaru do przesyłania w interfejsie użytkownika, a następnie użycie biblioteki IronWord do przetwarzania dokumentu, wyodrębnienia i wyświetlenia jego zawartości w twojej aplikacji.

Jakie są kroki do eksportowania dokumentu Word w ASP.NET Core?

Aby wyeksportować dokument Word w ASP.NET Core, użyj IronWord do utworzenia nowego dokumentu i dostarczenia użytkownikom funkcji pobierania go. Możesz określić nazwę pliku i używać metod IronWord do zapisu zawartości do pliku Word.

Czy mogę konwertować dokumenty Word do PDF w aplikacjach ASP.NET Core?

Tak, możesz konwertować dokumenty Word do PDF używając IronWord w aplikacjach ASP.NET Core. IronWord dostarcza metod do łatwego przekształcania dokumentów Word na format PDF, co ułatwia udostępnianie i dostępność.

Jakie formaty plików obsługuje aplikacja do importowania dokumentów Word?

Aplikacja obsługuje importowanie plików w formatach .DOC i .DOCX za pomocą biblioteki IronWord, co umożliwia przetwarzanie i wyświetlanie tych dokumentów w twojej aplikacji ASP.NET Core.

W jaki sposób JavaScript jest używany do ulepszenia aplikacji przetwarzającej dokumenty?

JavaScript jest używany do obsługi przesyłania plików, wysyłania żądań AJAX do serwera w celu przetworzenia dokumentu za pomocą IronWord oraz aktualizacji interfejsu użytkownika przetworzoną zawartością lub komunikatami o błędach, zapewniając płynne doświadczenie użytkownika.

Jakie są wymagania wstępne do rozwoju aplikacji przetwarzającej dokumenty Word w ASP.NET Core?

Aby rozwijać aplikację przetwarzającą dokumenty Word w ASP.NET Core, potrzebujesz podstawowej wiedzy na temat C# i ASP.NET Core, Visual Studio 2019 lub nowsze, lub Visual Studio Code z rozszerzeniem C#, oraz zainstalowany .NET Core SDK 3.1 lub nowszy.

Jak można zaprojektować interfejs użytkownika dla lepszego przetwarzania dokumentów?

Interfejs użytkownika można zaprojektować z obszarem przesyłania do wyboru dokumentów Word i obszarem wyświetlania zawartości do pokazywania przetworzonych treści. Niestandardowe CSS można użyć do ulepszenia projektu, aby stworzyć atrakcyjne i przyjazne dla użytkownika doświadczenie.

Jakie są potencjalne zastosowania integracji przetwarzania dokumentów Word w aplikacjach internetowych?

Potencjalne zastosowania to systemy zarządzania dokumentami i generatory raportów, gdzie integracja możliwości przetwarzania dokumentów Word z użyciem IronWord może usprawnić obsługę, edycję i procesy konwersji dokumentów w aplikacji internetowej.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie