Generate MS Word from database in MVC

Generate MS Word from Database in asp.net MVC using the DocX an open source library
 
At the end of this article we will be able to generate the following document.



Steps for creating Docx
  1. Create new MVC project in visual studio
  2. Download DocX.dll from HERE and add reference of this (.dll) to your project
  3. Add ADO.NET Entity Data Model to your project (for database)
  4. Add controller (GenerateDocumentController) to your project
  5. Add action method(GenerateDocument) to the controller
  6. Add view to (GenerateDocument) action method



Controller (GenerateDocumentController) Should look like this
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Novacode;
using System.IO;

namespace MyApp.Controllers
{
    public class GenerateDocumentController : Controller
    {
        
        public ActionResult GenerateDocument()
        {
            return View();
        }
        [HttpPost]
        public FileResult GenerateDocument(string gen)
        {
            DocX document = null;

            document = DocX.Create(Server.MapPath("~/mydoc.docx"), DocumentTypes.Document);

            Image img = document.AddImage(Server.MapPath("~/Images/mvc.png"));
            Picture pic = img.CreatePicture(100, 100);
            Paragraph picturepara = document.InsertParagraph();
            picturepara.Alignment = Alignment.center;
            picturepara.AppendPicture(pic).Alignment = Alignment.center;

            var headLineFormat = new Formatting();
            headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
            headLineFormat.Bold = true;
            headLineFormat.Size = 18.0;

            document.InsertParagraph(" ");
            string EnglishHeadingText = "List of Employees";
            Paragraph Eng = document.InsertParagraph(EnglishHeadingText, false, headLineFormat);
            Eng.Direction = Direction.LeftToRight;
            
            TExam.Models.TExam db = new TExam.Models.TExam();
            var teachers = (from T in db.Teachers
                            join d in db.Districts on T.DistrictID equals d.DistrictID
                            join p in db.Provinces on d.ProvinceID equals p.ProvinceID
                            where p.ProvinceID==1
                            select new
                            {
                                SerialNo = T.SrNo,
                                SchoolName = T.SchoolName,
                                Name = T.Name,
                                FatherName = T.FatherName,
                                Marks = T.Marks
                            }).ToList();


            Table tbl = document.AddTable(teachers.Count+1, 5);
            tbl.Alignment = Alignment.center;
            tbl.Design = TableDesign.LightGridAccent6;
            tbl.SetDirection(Direction.RightToLeft);

            tbl.Rows[0].Cells[0].Paragraphs.First().Append("شماره");
            tbl.Rows[0].Cells[1].Paragraphs.First().Append("نوم");
            tbl.Rows[0].Cells[2].Paragraphs.First().Append("دپلارنوم");
            tbl.Rows[0].Cells[3].Paragraphs.First().Append("دښوونځی نوم");
            tbl.Rows[0].Cells[4].Paragraphs.First().Append("نمبری");
            int rowno = 1;
            foreach(var itm in teachers)
            {
                tbl.Rows[rowno].Cells[0].Paragraphs.First().Append(itm.SerialNo.ToString());
                tbl.Rows[rowno].Cells[1].Paragraphs.First().Append(itm.Name.ToString());
                tbl.Rows[rowno].Cells[2].Paragraphs.First().Append(itm.FatherName.ToString());
                tbl.Rows[rowno].Cells[3].Paragraphs.First().Append(itm.SchoolName.ToString());
                tbl.Rows[rowno].Cells[4].Paragraphs.First().Append(itm.Marks.ToString());
                rowno++;
            }
           
            document.InsertTable(tbl);

            // For  Farsi, Arabic and Urdu.
            // document.SetDirection(Direction.RightToLeft);

            document.Save();
            MemoryStream ms = new MemoryStream();
            document.SaveAs(ms);
            return File(ms.ToArray(), "application/msword", "report.docx");
        }
    }
}

Add Empty view to GenerateDocument action method. The view should look like this.
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>GenerateDocument</title>
    @Scripts.Render("~/bundles/jqueryLTR")
    @Scripts.Render("~/bundles/bootstrapLTR")
    @Styles.Render("~/content/cssLTR")
</head>
<body>
    <div class="container">
        <div class="jumbotron">
            @using (Html.BeginForm())
            {
                <div class="form-horizontal">
                    <button type="submit" class="btn btn-success btn-lg"><i class="fa fa-list-alt"></i> Generate document</button>
                </div>
            }
        </div>
    </div>
</body>
</html>

Post a Comment