asp.net MVC

How to create word document file using asp.net MVC?

How to create word document file using asp.net MVC?, someone asked me to explain?

In this step-by-step article descrbes how to create a MS word document file using asp.net. The sample code in this article demonstrates how to insert paragraphs with text programmatically. Inorder to create we need to install docX using nuget package console.

PM> Install-Package DocX

Step 1: Create a class and name it as Document in the model folder.

public class Document
    {
        public string txtContent { get; set; }
    }

Step 2: Right click on the "Controllers" folder and add "doc" controller. Copy and paste the following code. Please make sure to include "MVC_tutorials.Models" namespace.

using MVC_tutorials.Models;
using Novacode;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_tutorials.Controllers
{
    public class docController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Documentdocument)
        {
            string fileName = Server.MapPath(@"~\DocXExample.docx");
            // Create a document in memory:
            var doc = DocX.Create(fileName);
            // Insert a paragrpah:
           doc.InsertParagraph(document.txtContent);
            // Save to the output directory:
           doc.Save();
           TempData["Message"] = "document created successfully.";
            return View();
        }
    }
}

Step 3: Right click on the "Index" action method in the "docController" and add "Index" view. Copy and paste the following code.

@model MVC_tutorials.Models.Document
@{
   ViewBag.Title = "create document in asp.net MVC";
}
<style type="text/css">
    .btn {
        width: 150px;
        height: 50px;
        background: #00BCD4;
        border-style: solid;
        border-color: white;
        color: white;
    }
</style>
<div style="padding-top: 15px">
    <h2 style="color: #FF5722">create document in asp.net MVC
    </h2>
    @using (@Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        if (TempData["Message"] != null)
        {
        <p style="font-family: Arial; font-size: 16px; font-weight: 200; color: #56772F">@TempData["Message"]</p>
        }
        @Html.TextAreaFor(model => model.txtContent, new { Class = "mytextstyle", rows = 5, Style = "width:450px", placeholder = "type your content and save it in adocument." })
        <br />
        <input type="submit" value="create document" class="btn" />
    }
</div>

Output:

create ms word document file using asp.net MVC

Post your comments / questions