I solved my problem using the below process:
I posted the form when user clicks on Export to Excel:
$(function () {
$('a#lkDealExport').click(
(function (e) {
var originalAction = $(this).parents('form#DataFrm').attr('action');
$('form#DataFrm').attr("action", $(e.target).attr("data-formaction"));
$('form#DataFrm').submit();
$('form#DataFrm').attr("action", originalAction); // reset the action back to orginal action after the export to excel is executed.
return false;
})
);
});
If we don't post the form, devExpress grid user selection (sorting, pagination and filter) is not exporting to excel.
In post action method, I included the below code:
using (MemoryStream stream = new MemoryStream())
{
if (EventListModel.gridData.Count() > 0) // This will avoid exporting header information when search returns 0 results.
{
GridViewExtension.WriteXlsx(SubmissionGridViewHelper.Instance.Settings, EventListModel.gridData, stream);
}
Then we can pass this MemoryStream to the method that is loading openXML
if (eventLogStream.Length > 0) // Insert data into excel only when memory stram is not empty.
{
XLWorkbook eventLogWorkBook = new XLWorkbook(eventLogStream);
var firstPossibleAddres = eventLogWorkBook.Worksheet(1).FirstCellUsed().Address;
var lastPossibleAddress = eventLogWorkBook.Worksheet(1).LastCellUsed().Address;
worksheet.Cell(++rowIndex, 1).Value = eventLogWorkBook.Worksheet(1).Range(firstPossibleAddres, lastPossibleAddress).RangeUsed();
rowIndex += eventLogWorkBook.Worksheet(1).Range(firstPossibleAddres, lastPossibleAddress).RowCount();
}
Hope this will be helpful for others.