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 (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
@{
var grid = "LunchGrid";
}
@(Html.Awe().Grid(grid)
.Url(Url.Action("GetItems"))
.Mod(o => o.ColumnsSelector())
.Persistence(Persistence.Session)
.Resizable()
.Height(350)
.Columns(
new Column { Bind = "Id", Width = 80 },
new Column { Bind = "Person" },
new Column { Bind = "Food.Name" },
new Column { Bind = "Date", Width = 150 },
new Column { Bind = "Price", ClientFormatFunc = "priceFormat", Width = 110 },
new Column { Bind = "Country.Name", Header = "Country" },
new Column { Bind = "Chef.FirstName,Chef.LastName", Prop = "ChefName", Header = "Chef" },
new Column { Bind = "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>@Html.Awe().CheckBox("allPages") All pages</label>
<label>@Html.Awe().CheckBox("loadDelay") Load delay (3 seconds)</label>
</div>
<script>
$(function() {
$('#exportAll').click(function() {
getFile('@Url.Action("ExportAllToExcel", "GridExportToExcelDemo")');
});
$('#exportGrid').click(function() {
getFile('@Url.Action("ExportGridToExcel", "GridExportToExcelDemo")');
});
$('#exportGridPdf').click(function() {
getFile('@Url.Action("ExportGridToPdf", "GridExportToExcelDemo")');
});
$('#exportGridTxt').click(function() {
getFile('@Url.Action("ExportGridToTxt", "GridExportToExcelDemo")');
});
});
async function getFile(url) {
// Collect request parameters from the grid
var grid = $('#@(grid)');
var req = grid.data('api').getRequest();
var expCols = getExpColumns(grid);
var formData = new FormData();
// Add visible columns info
expCols.forEach((col, i) => {
formData.append(`expColumns[${i}].Name`, col.name);
formData.append(`expColumns[${i}].Header`, col.header);
formData.append(`expColumns[${i}].Width`, col.width);
formData.append(`expColumns[${i}].Hidden`, col.hidden);
});
// Add request parameters
req.forEach(val => {
formData.append(val.name, val.value);
});
formData.append('allPages', $('#allPages').val());
formData.append('loadDelay', $('#loadDelay').val());
try {
const loadAnim = awem.loadingAnim({ cont: $('body') });
loadAnim.start();
// Make POST request using fetch
let response = await fetch(url, {
method: "POST",
body: formData
});
if (!response.ok) {
throw new Error(`Server returned ${response.status} ${response.statusText}`);
}
// Extract filename from Content-Disposition header
const contentDisposition = response.headers.get("Content-Disposition");
let filename = contentDisposition.match(/filename=([^;]+)/)?.[1].trim() || 'download.xls';
let blob = await response.blob();
loadAnim.stop();
// Trigger file download
const downloadUrl = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(downloadUrl);
} catch (error) {
loadAnim.stop();
console.error("Download failed:", error);
}
}
function getExpColumns(g) {
return awef.select(g.data('o').columns,
function (col) {
return { name: col.T || col.P, header: col.Header, hidden: !!col.Hid, width: col.W || col.Mw || col.needw };
});
}
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();
}
public IActionResult GetItems(GridParams g)
{
return Json((BuildGridModel(g)).ToDto());
}
private GridModel<Lunch> BuildGridModel(GridParams g)
{
var query = Db.Lunches.AsQueryable();
var gmb = new GridModelBuilder<Lunch>(query, g)
{
KeyProp = o => o.Id,
Map = o => new
{
o.Id,
o.Person,
FoodName = o.Food.Name,
o.Location,
o.Price,
Date = o.Date.ToShortDateString(),
CountryName = o.Country.Name,
ChefName = o.Chef.FullName
},
MakeFooter = info =>
{
if (info.Level == 0)
{
return new
{
Id = "Total",
Price = "Min: " + info.Items.Min(o => o.Price),
Date = "Max: " + info.Items.Max(o => o.Date).ToShortDateString()
};
}
return new
{
Price = "Min: " + info.Items.Min(o => o.Price),
Date = "Max: " + info.Items.Max(o => o.Date).ToShortDateString()
};
}
};
return gmb.BuildModel();
}
private IEnumerable<ExpColumn> addServerFormatting(IEnumerable<ExpColumn> columns)
{
var priceColumn = columns.SingleOrDefault(o => o.Name == "Price");
if (priceColumn != null)
{
priceColumn.ClientFormatFunc = (lunch, property) =>
{
var value = lunch.GetType().GetProperty("Price")?.GetValue(lunch).ToString();
if (!string.IsNullOrEmpty(value))
{
value += " USD";
}
return value;
};
priceColumn.Width = 200;
}
return columns;
}
[HttpPost]
public async Task<IActionResult> ExportGridToExcel(
GridParams g,
IEnumerable<ExpColumn> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var gridModel = BuildGridModel(g);
var workbook = new GridExcelBuilder(expColumns.Where(o => !o.Hidden)).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<ExpColumn> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var gridModel = BuildGridModel(g);
var res = new GridTxtBuilder(expColumns.Where(o => !o.Hidden)).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<ExpColumn> expColumns,
bool? allPages,
bool? loadDelay)
{
if (loadDelay == true)
{
await Task.Delay(3000);
}
if (allPages.HasValue && allPages.Value)
{
g.Paging = false;
}
var gridModel = BuildGridModel(g);
var builder = new GridPdfBuilder(addServerFormatting(expColumns.Where(o => !o.Hidden)));
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,
FoodName = o.Food.Name,
o.Location,
CountryName = o.Country.Name,
ChefName = o.Chef.FullName
}).ToList();
var properties = new[] { "Id", "Person", "FoodName", "CountryName", "ChefName", "Location" };
var headers = new[] { "Id", "Person", "Food", "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");
}
}
}
Comments