Demos/Grid/GridExportToExcelDemoController.cs
using System.Threading.Tasks;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using AwesomeWebFormsDemo.Data;
using AwesomeWebFormsDemo.Models;
using AwesomeWebFormsDemo.Utils;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.Web.Mvc;
using NPOI.HSSF.UserModel;
using Omu.AwemWebForms.Export;
using Omu.AwesomeWebForms;
namespace AwesomeWebFormsDemo.Controllers.Demos.Grid
{
public class GridExportToExcelDemoController : Controller
{
public ActionResult Index()
{
return View();
}
#region Grid
public ActionResult GetItems(GridParams g)
{
var (gridModel, _) = BuildGridModel(g);
return this.AweJson(gridModel.ToDto());
}
private (GridModel<Lunch> gridModel, GridModelBuilder<Lunch> gmb) BuildGridModel(GridParams g)
{
var query = Db.Lunches.AsQueryable();
var gmb = new GridModelBuilder<Lunch>(query, g);
gmb.KeyProp = o => o.Id;
var nr = 1;
gmb.ComputeProp(o => nr++ + (g.Spage - 1) * g.PageSize, "Nr");
return (gmb.BuildModel(), gmb);
}
[HttpPost]
public async Task<ActionResult> ExportGridToExcel(
GridParams g,
IEnumerable<GridExpCol> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var (gridModel, gmb) = BuildGridModel(g);
var props = gmb.GetProps();
var workbook = new GridExcelBuilder(expColumns.Where(o => !o.Hidden))
{
Props = props
}
.Build(gridModel);
using (var stream = new MemoryStream())
{
workbook.Write(stream);
stream.Close();
return File(stream.ToArray(), "application/vnd.ms-excel", "lunches.xls");
}
}
[HttpPost]
public async Task<ActionResult> ExportGridToTxt(
GridParams g,
IEnumerable<GridExpCol> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var (gridModel, gmb) = BuildGridModel(g);
var props = gmb.GetProps();
var res = new GridTxtBuilder(expColumns.Where(o => !o.Hidden))
{
Props = props
}
.Build(gridModel);
using (var memoryStream = new MemoryStream())
{
using (var writer = new StreamWriter(memoryStream))
{
writer.WriteLine(res);
}
return File(memoryStream.ToArray(), "text/plain", "lunches.txt");
}
}
[HttpPost]
public async Task<ActionResult> ExportGridToPdf(
GridParams g,
IEnumerable<GridExpCol> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var (gridModel, gmb) = BuildGridModel(g);
var props = gmb.GetProps();
var builder = new GridPdfBuilder(AddServerFormatting(expColumns.Where(o => !o.Hidden)))
{
Props = props
};
var workStream = new MemoryStream();
var writer = new PdfWriter(workStream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello World!"));
document.Add(new Paragraph("Export to pdf example (using iText7)"));
document.Add(new Paragraph(new Text("\n")));
var table = builder.Build(gridModel);
document.Add(table);
writer.SetCloseStream(false);
document.Close();
var byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return File(workStream, "application/pdf", "lunches.pdf");
}
/// <summary>
/// Demonstrates the simplest way of creating an excel workbook
/// it exports all the lunches records, without taking into account any sorting/paging that is done on the client side
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult> ExportAllToExcel(bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet("sheet1");
var res = Db.Lunches.ToArray();
var items = res.Select(
o => new
{
o.Id,
o.Person,
DishName = o.Dish.Name,
o.Location,
CountryName = o.Country.Name,
ChefName = o.Chef.FullName
}).ToList();
var properties = new[] { "Id", "Person", "DishName", "CountryName", "ChefName", "Location" };
var headers = new[] { "Id", "Person", "Dish", "Country", "Chef", "Location" };
var headerRow = sheet.CreateRow(0);
// create header
for (int i = 0; i < properties.Length; i++)
{
var cell = headerRow.CreateCell(i);
cell.SetCellValue(headers[i]);
}
// fill content
for (int i = 0; i < items.Count; i++)
{
var rowIndex = i + 1;
var row = sheet.CreateRow(rowIndex);
for (int j = 0; j < properties.Length; j++)
{
var cell = row.CreateCell(j);
var o = items[i];
cell.SetCellValue(o.GetType().GetProperty(properties[j]).GetValue(o, null).ToString());
}
}
using (var stream = new MemoryStream())
{
workbook.Write(stream);
stream.Close();
return File(stream.ToArray(), "application/vnd.ms-excel", "lunches.xls");
}
}
private IEnumerable<GridExpCol> AddServerFormatting(IEnumerable<GridExpCol> columns)
{
var priceColumn = columns.SingleOrDefault(o => o.Bind == "Price");
if (priceColumn != null)
{
priceColumn.ClientFormatFunc = (item, expCol) =>
{
var expando = item as IDictionary<string, object>;
var price = expando?["Price"]?.ToString();
if (!string.IsNullOrEmpty(price))
{
price += " USD";
}
return price;
};
priceColumn.Width = 200;
}
return columns;
}
#endregion
#region PivotGrid
private PivotGridModel BuildPivotGridModel(PivotGridParams g)
{
var source = Db.Lunches.AsQueryable();
var pgmb = new PivotGridModelBuilder();
var data = pgmb.Build(source, g);
return data;
}
public ActionResult ExportPivotGridToExcel(PivotGridParams g)
{
var pivotGridModel = BuildPivotGridModel(g);
var workbook = new PivotGridExcelBuilder(g)
{
Headers = new Dictionary<string, string>
{
{ "Dish.Name", "Dish" },
{ "Country.Name", "Country" },
{ "Chef.FirstName,Chef.LastName", "Chef" }
}
}.Build(pivotGridModel);
using (var stream = new MemoryStream())
{
workbook.Write(stream);
stream.Close();
return File(stream.ToArray(), "application/vnd.ms-excel", "lunchesPivotData.xls");
}
}
public ActionResult ExportPivotGridToTxt(PivotGridParams g)
{
var pivotGridModel = BuildPivotGridModel(g);
var builder = new PivotGridTxtBuilder(g)
{
Headers = new Dictionary<string, string>
{
{ "Dish.Name", "Dish" },
{ "Country.Name", "Country" },
{ "Chef.FirstName,Chef.LastName", "Chef" }
}
};
var txt = builder.Build(pivotGridModel);
using (var memoryStream = new MemoryStream())
{
using (var writer = new StreamWriter(memoryStream))
{
writer.WriteLine(txt);
}
return File(memoryStream.ToArray(), "text/plain", "lunchesPivotData.txt");
}
}
public ActionResult ExportPivotGridToPdf(PivotGridParams g)
{
var pivotGridModel = BuildPivotGridModel(g);
var builder = new PivotGridPdfBuilder(g)
{
Headers = new Dictionary<string, string>
{
{ "Dish.Name", "Dish" },
{ "Country.Name", "Country" },
{ "Chef.FirstName,Chef.LastName", "Chef" }
}
};
var workbook = builder.Build(pivotGridModel);
bool landscape = false;
if (PivotGridPdfBuilder.ShouldUseLandscape(workbook))
{
landscape = true;
}
var pageSize = landscape ? PageSize.A4.Rotate() : PageSize.A4;
var workStream = new MemoryStream();
var writer = new PdfWriter(workStream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf, pageSize);
document.Add(new Paragraph("Hello World!"));
document.Add(new Paragraph("Export to pdf example (using iText7)"));
document.Add(new Paragraph(new Text("\n")));
document.Add(workbook);
writer.SetCloseStream(false);
document.Close();
var byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return File(workStream, "application/pdf", "lunches.pdf");
}
#endregion
}
}