Export grid to Excel, Pdf and txt (csv)
This demo is showing how to build the grid model and use it to export the data in various formats (xls, pdf, txt)
using external libraries and custom code.
Export the content of a grid to excel, pdf and txt file.
To create an excel file we're using the NPOI library.
For exporting to Pdf the iText7 library is used.
To get the entire source code you can download this demo.
For exporting to Pdf the iText7 library is used.
To get the entire source code you can download this demo.
GridExportToExcelDemo/Index.cshtml
@{
var gridId = "LunchGrid";
var pivotGridId = "PivotGrid";
}
@(Html.Awex().Grid<Lunch>(gridId)
.Main()
.Url(Url.Action("GetItems"))
.Persistence(Persistence.Session)
.Resizable()
.Height(350)
.Columns(b =>
{
b.Add(new Column {ClientFormat = ".(Nr)", Header = "Nr", Width = 75});
b.Add(o => o.Id, new Column { Width = 80 });
b.Add(o => o.Person);
b.Add(o => o.Dish.Name);
b.Add(o => o.Date, new Column { Width = 150 });
b.Add(o => o.Price, new Column { ClientFormatFunc = "priceFormat", Width = 110 });
b.Add(o => o.Country.Name, new Column { Header = "Country" });
b.Add(o => new { o.Chef.FirstName, o.Chef.LastName });
b.Add(o => o.Location);
})
)
<br />
<div class="btn-cont">
<button id="exportGrid" type="button" class="awe-btn">Export grid to excel</button>
<button id="exportGridPdf" type="button" class="awe-btn">Export grid to Pdf</button>
<button id="exportGridTxt" type="button" class="awe-btn">Export grid to txt (csv)</button>
<button id="exportAll" type="button" class="awe-btn">Export all records to excel</button>
</div>
<div class="btn-cont">
<label class="o-items-center">@Html.Awe().CheckBox("allPages") All pages</label>
<label class="o-items-center">@Html.Awe().CheckBox("loadDelay") Load delay (3 seconds)</label>
</div>
<script>
$(function () {
$('#exportAll').click(function () {
gridDownloadFile('@Url.Action("ExportAllToExcel", "GridExportToExcelDemo")');
});
$('#exportGrid').click(function () {
gridDownloadFile('@Url.Action("ExportGridToExcel", "GridExportToExcelDemo")');
});
$('#exportGridPdf').click(function () {
gridDownloadFile('@Url.Action("ExportGridToPdf", "GridExportToExcelDemo")');
});
$('#exportGridTxt').click(function () {
gridDownloadFile('@Url.Action("ExportGridToTxt", "GridExportToExcelDemo")');
});
});
function gridDownloadFile(url) {
return getFile('@gridId', url);
}
function pivotGridDownloadFile(url) {
return getFile('@pivotGridId', url, true);
}
function getFile(gridId, url, pivot = false) {
awe.use({ useMod: 'util/gridExportUtil' }).then(function (f) {
f.getFile({
gridId: gridId,
url: url,
pivot: pivot,
allPages: $('#allPages').val(),
loadDelay: $('#loadDelay').val()
});
});
}
function priceFormat(lunch, prop) {
var price = lunch[prop];
return price + ' USD';
}
</script>
Demos/Grid/GridExportToExcelDemoController.cs
public class GridExportToExcelDemoController : Controller
{
public IActionResult Index()
{
return View();
}
#region Grid
public IActionResult 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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 IActionResult 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 IActionResult 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 IActionResult 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
}
Pivot Grid
Export the content of a pivot grid to excel, pdf and txt file (csv).
To create an excel file we're using the NPOI library.
For exporting to Pdf the iText7 library is used.
To get the entire source code you can download this demo.
For exporting to Pdf the iText7 library is used.
To get the entire source code you can download this demo.
GridExportToExcelDemo/Index.cshtml
<h2>Pivot Grid</h2>
@(Html.Awex().PivotGrid<Lunch>(new PivotGridOpt
{
Id = pivotGridId,
Url = Url.Action("GetLunchGridData", "PivotGrid"),
ContentHeight = 300
})
.Fields(b => {
b.Add(o => o.Person);
b.Add(o => o.Dish.Name, new Field { Header = "Dish" });
b.Add(o => o.Country.Name, new Field { Header = "Country" });
b.Add(o => o.Location);
b.Add(o => o.Price);
b.Add(o => new { o.Chef.FirstName, o.Chef.LastName }, new Field { Header = "Chef" });
})
.Rows(b => {
b.Add(o => o.Person);
b.Add(o => o.Dish.Name);
})
.Columns(b => {
b.Add(o => new { o.Chef.FirstName, o.Chef.LastName });
})
.Measures(b => {
b.Add(o => o.Price, Agg.Average);
})
)
<div class="btn-cont">
<button id="exportPivotGrid" type="button" class="awe-btn" onclick="pivotGridDownloadFile('@Url.Action("ExportPivotGridToExcel", "GridExportToExcelDemo")')">Export pivot grid to excel</button>
<button id="exportPivotGridPdf" type="button" class="awe-btn" onclick="pivotGridDownloadFile('@Url.Action("ExportPivotGridToPdf", "GridExportToExcelDemo")')">Export pivot grid to Pdf</button>
<button id="exportPivotGridTxt" type="button" class="awe-btn" onclick="pivotGridDownloadFile('@Url.Action("ExportPivotGridToTxt", "GridExportToExcelDemo")')">Export pivot grid to txt</button>
</div>
Demos/Grid/GridExportToExcelDemoController.cs
public IActionResult 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");
}
}
Demos/Grid/GridExportToExcelDemoController.cs
public IActionResult 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");
}
Demos/Grid/GridExportToExcelDemoController.cs
public IActionResult 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");
}
}
Comments