我使用以下过程解决了我的问题:
当用户单击“导出到 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;
})
);
});
如果我们不发布表单,devExpress 网格用户选择(排序、分页和过滤)不会导出到 Excel。
在 post action 方法中,我包含了以下代码:
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);
}
然后我们可以将此 MemoryStream 传递给正在加载 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();
}
希望这对其他人有帮助。