How to add Button for downloading excel file in Acumatica

纵饮孤独 提交于 2020-01-11 13:15:32

问题


I'm trying to add button to Users Maintenance and on button's click download excel file, containing some data. I have created PXAction and it's method as above:

public PXAction<Users> getUsers;

[PXUIField(DisplayName = "Get Users", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select,Visible = true), PXButton(CommitChanges = true)]
public IEnumerable GetUsers(PXAdapter adapter)
{
    var accessByRoles = PXSelect<RolesInGraph>.Select(this.Base);
    var usersByRole = PXSelect<UsersInRoles>.Select(this.Base);
    var dt = GetTable();//GetTable returns some DataTable just for test now
    XLWorkbook workbook = new XLWorkbook();
    workbook.Worksheets.Add(dt, "UserAccessRigths");
    using (MemoryStream MyMemoryStream = new MemoryStream())
    {
        workbook.SaveAs(MyMemoryStream);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=\"UserAccessRigths.xlsx\"");
        HttpContext.Current.Response.AppendHeader("Content-Length", MyMemoryStream.ToArray().Length.ToString());
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.BinaryWrite(MyMemoryStream.ToArray());
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
    return null;
}

Everything work but the part where the download in the browser must start. I'm getting as response the excel, but it's not being downloaded. Here is the response I'm getting in the browser:

I will be very grateful if someone can help me.
Thanks in advance


回答1:


Try PXRedirectToFileException to redirect the user browser to the Excel file. Default behavior from mainstream browser is to detect Excel mime type by extension and initiate a download. Second parameter of PXRedirectToFileException is used to force download.

throw new PXRedirectToFileException(new PX.SM.FileInfo(Guid.NewGuid(),
                                                       "UserAccessRigths.xlsx",
                                                       null,
                                                       MyMemoryStream.ToArray()),
                                    true);


来源:https://stackoverflow.com/questions/43998006/how-to-add-button-for-downloading-excel-file-in-acumatica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!