Step 1:- Open Visual Studio 2015 => Go to File Menu
=> New => Project...
Step 2:- In the Installed Templates list, select Visual
C# => Web
Step 3:- Select ASP.Net Web Application from
the Web list => Type MvcWebGrid in the Name box and click OK
Step 4:- Select Empty template from
ASP.NET Templates List and Checked MVC check box under Add
folders and core references for:
Step 5:- Right-click Models folder in
Solution Explorer => Add => Click
New Items...
Step 6:- Select Class from the Visual C# list
= > Type Product.cs in the name box and click
Add
Step 7:- Copy Past following code in the Product.cs
public class Product
{
public int
ProductId { get; set; }
public string
ProductName { get; set; }
public string ProductCode
{ get; set; }
public int
ProductQty { get; set; }
public decimal
ProductWeight { get; set; }
public string
ProductDesc { get; set; }
}
Step 8:- Right-click Controllers folder in
Solution Explorer => Add => Click
Controllers...
Step 9:- Select MVC 5 Controller - Empty from
the controller list = > Click Add
Step 10:- Type ProductController in the Controller name box and click Add
Step 11:- Add following Action method in Product
Controller
using
iTextSharp.text;
using
iTextSharp.text.pdf;
using
iTextSharp.tool.xml;
using
MvcWebGrid.Models;
using System;
using
System.Collections.Generic;
using
System.IO;
using
System.Linq;
using
System.Text;
using
System.Web.Helpers;
using
System.Web.Mvc;
using
System.Web.UI;
using System.Web.UI.WebControls;
private List<Product>
getProducts()
{
List<Product>
listProduct = new List<Product>();
listProduct.Add(new Product {
ProductId = 1, ProductName = "Parle G", ProductCode = "P001",
ProductQty = 12, ProductWeight = 820, ProductDesc = "Parle
G" });
listProduct.Add(new Product {
ProductId = 2, ProductName = "CNC", ProductCode = "P002",
ProductQty = 24, ProductWeight = 2400, ProductDesc = "CNC" });
listProduct.Add(new Product {
ProductId = 3, ProductName = "Krackjack", ProductCode = "P003",
ProductQty = 12, ProductWeight = 960, ProductDesc = "Krackjack" });
listProduct.Add(new Product {
ProductId = 4, ProductName = "20-20 Cookies",
ProductCode = "P004", ProductQty = 12, ProductWeight = 820, ProductDesc = "20-20
Cookies" });
listProduct.Add(new Product {
ProductId = 5, ProductName = "Monaco-Salted Craker",
ProductCode = "P005", ProductQty = 12, ProductWeight = 900, ProductDesc = "Monaco-Salted
Craker" });
listProduct.Add(new Product {
ProductId = 6, ProductName = "Hide & Seek Choco Chips",
ProductCode = "P006", ProductQty = 24, ProductWeight = 720, ProductDesc = "Hide
& Seek Choco Chips" });
listProduct.Add(new Product {
ProductId = 7, ProductName = "Hide & Seek Bourbon",
ProductCode = "P007", ProductQty = 12, ProductWeight = 780, ProductDesc = "Hide
& Seek Bourbon" });
listProduct.Add(new Product {
ProductId = 8, ProductName = "Parle Marie",
ProductCode = "P008", ProductQty = 24, ProductWeight = 2400, ProductDesc = "Parle
Marie" });
listProduct.Add(new Product {
ProductId = 9, ProductName = "Coconut Cookies",
ProductCode = "P009", ProductQty = 12, ProductWeight = 820, ProductDesc = "Coconut
Cookies" });
listProduct.Add(new Product {
ProductId = 10, ProductName = "Good Day", ProductCode = "P0010",
ProductQty = 12, ProductWeight = 820, ProductDesc = "Good
Day" });
return listProduct;
}
// GET: Product
public ActionResult Index()
{
List<Product>
listProduct = getProducts();
return View(listProduct);
}
[HttpPost]
public void
ExportToExcel()
{
List<Product>
list = getProducts();
WebGrid grid = new WebGrid(source:
list, canPage: false, canSort: false);
string gridData =
grid.GetHtml(
columns: grid.Columns(
grid.Column(columnName: "ProductName",
header: "Product Name"),
grid.Column(columnName: "ProductCode",
header: "Product Code"),
grid.Column(columnName: "ProductQty",
header: "Product Qty"),
grid.Column(columnName: "ProductWeight", header:
"Product
Weight"),
grid.Column(columnName: "ProductDesc",
header: "Product Desc")
)
).ToString();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;
filename=Products.xls");
Response.ContentType = "application/excel";
Response.Write(gridData);
Response.End();
}
[HttpPost]
public void
ExportToExcelWithFormat()
{
List<Product>
list = getProducts();
GridView
gridView = new GridView();
gridView.DataSource = list;
gridView.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;
filename=Products.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
for (int i = 0;
i < gridView.HeaderRow.Cells.Count; i++)
{
gridView.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
gridView.HeaderRow.Cells[i].Style.Add("font-weight", "bold");
gridView.HeaderRow.Cells[i].Style.Add("color", "#fff");
}
int j = 1;
foreach (GridViewRow gvrow in
gridView.Rows)
{
if (j
<= gridView.Rows.Count)
{
if (j % 2
!= 0)
{
for (int k = 0;
k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gridView.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
[HttpPost]
public FileContentResult
ExportToCSV()
{
List<Product>
list = getProducts();
StringBuilder sb = new StringBuilder();
Type type = typeof(Product);
var props =
type.GetProperties();
// Write the header
sb.AppendLine(string.Join(",",
props.Select(p => p.Name)));
// Write the item
foreach (var item in list)
{
sb.AppendLine(string.Join(",",
props.Select(p => p.GetValue(item))));
}
string csv =
sb.ToString();
return File(new UTF8Encoding().GetBytes(csv),
"text/csv", "Product.csv");
}
[HttpPost]
public FileContentResult
ExportToPDF1()
{
List<Product>
list = getProducts();
WebGrid grid = new WebGrid(source:
list, canPage: false, canSort: false);
string gridData =
grid.GetHtml(
columns: grid.Columns(
grid.Column(columnName: "ProductName",
header: "Product Name"),
grid.Column(columnName: "ProductCode",
header: "Product Code"),
grid.Column(columnName: "ProductQty",
header: "Product Qty"),
grid.Column(columnName: "ProductWeight",
header: "Product Weight"),
grid.Column(columnName: "ProductDesc",
header: "Product Desc")
)
).ToString();
StringBuilder sbCss =
new StringBuilder();
sbCss.AppendLine("table
{ margin: 4px; border-collapse: collapse; width: 700px; color:#333333;}");
sbCss.AppendLine("th
{ border: 1px solid #000; padding: 5px; background-color: #507CD1; font-weight:
bold; color: #fff; }");
sbCss.AppendLine("td
{ border: 1px solid #000; padding: 5px; }");
sbCss.AppendLine("tr:nth-of-type(odd)
{ background-color: #EFF3FB; color: #000; }");
string exportData = String.Format("<html><head><style>{0}</style></head><body>{1}</body></html>", sbCss,
gridData);
using (MemoryStream stream
= new MemoryStream())
{
StringReader sr = new StringReader(exportData);
Document pdfDoc
= new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer
= PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer,
pdfDoc, sr);
pdfDoc.Close();
return
File(stream.ToArray(), "application/pdf", "Product.pdf");
}
}
[HttpPost]
[ValidateInput(false)]
public FileContentResult
ExportToPDF2(string GridHtml)
{
using (MemoryStream stream
= new MemoryStream())
{
StringReader sr = new StringReader(GridHtml);
Document pdfDoc
= new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer
= PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer,
pdfDoc, sr);
pdfDoc.Close();
return
File(stream.ToArray(), "application/pdf", "Product.pdf");
}
}
Note:-
If you get the Error regarding PdfWriter and XMLWorkerHelper Class, Install the following DLL using NuGet Package Manager
in Visual Studio
iTextSharp
itextsharp.xmlworker
Step 12:- To Add View of Action Method,
Right-click inside the Index Action body => Click Add View => Click Add
Step 13:- Double-click Index.cshtml in Solution Explorer to open and decorate Index.cshtml view with following
code
@model IEnumerable<MvcWebGrid.Models.Product>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@{
var webGrid = new WebGrid(Model,
canPage: false);
}
<b>This
WebGrid Exporting on "Export to PDF 2" button click</b>
<div class="WebGridContainer">
@webGrid.GetHtml(
tableStyle: "Grid-table",
headerStyle: "Grid-header",
footerStyle: "Grid-footer",
rowStyle: "Grid-row",
alternatingRowStyle: "Grid-alt",
selectedRowStyle: "Grid-selected",
caption: "",
displayHeader: true,
fillEmptyRows: false,
emptyRowCellValue: "",
columns: webGrid.Columns(
webGrid.Column(columnName: "ProductName",
header: "Product Name"),
webGrid.Column(columnName: "ProductCode",
header: "Product Code"),
webGrid.Column(columnName: "ProductQty",
header: "Product Qty"),
webGrid.Column(columnName: "ProductWeight",
header: "Product Weight"),
webGrid.Column(columnName: "ProductDesc",
header: "Product Desc")
))
</div>
<hr />
@using
(Html.BeginForm(actionName: "ExportToExcel",
controllerName: "Product", method: FormMethod.Post))
{
<input id="btnExportToExcel" type="submit" value="Export
to Excel" />
}
@using
(Html.BeginForm(actionName: "ExportToExcelWithFormat",
controllerName: "Product", method: FormMethod.Post))
{
<input id="btnExportToExcelWithFormat" type="submit" value="Export
to Excel With Formated Output" />
}
@using
(Html.BeginForm(actionName: "ExportToCSV",
controllerName: "Product", method: FormMethod.Post))
{
<input id="btnExportToCSV" type="submit" value="Export
to CSV" />
}
@using
(Html.BeginForm(actionName: "ExportToPDF1",
controllerName: "Product", method: FormMethod.Post))
{
<input id="btnExportToPDF1" type="submit" value="Export
to PDF 1" />
}
@using
(Html.BeginForm(actionName: "ExportToPDF2",
controllerName: "Product", method: FormMethod.Post))
{
<input type="hidden" name="GridHtml" value="GridHtml" />
<input id="btnExportToPDF2" type="submit" value="Export
to PDF 2" />
}
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function () {
$('#btnExportToExcel').click(function () {
window.location.href = 'Product/ExportToExcel';
});
$('#btnExportToExcelWithFormat').click(function () {
window.location.href = 'Product/ExportToExcelWithFormat';
});
$('#btnExportToCSV').click(function () {
window.location.href = 'Product/ExportToCSV';
});
$('#btnExportToPDF1').click(function () {
window.location.href = 'Product/ExportToPDF1';
});
$('#btnExportToPDF2').click(function () {
$("input[name='GridHtml']").val($(".WebGridContainer").html());
window.location.href = 'Product/ExportToPDF2';
});
});
</script>
<style>
.Grid-table {margin: 4px;border-collapse: collapse;color: #333333;}
.Grid-table th, .Grid-table td {border: 1px solid #000;padding: 5px;}
.Grid-header {background-color: #b3ffb3;font-weight: bold;color: #000000;}
.Grid-header a:hover {text-decoration: underline;color: #ff6a00;}
.Grid-footer {background-color: #b3ffb3;font-weight: bold;color: #000000;}
.Grid-alt {background-color: #EFF3FB;color: #000;}
.Grid-selected {background-color: #ffd800;color: #000;}
.Grid-description {width: auto;}
</style>
All done
Run Project
Output Look like…