通过ext.net按钮下载Excel文件

时间:2016-06-13 07:01:00

标签: c# asp.net epplus ext.net

在我的应用程序中,我使用web表单+ ext.net,EPPlus。我想在Excel文件中导出如下:

<ext:Button
                                runat="server"
                                Text="Экспорт в Excel"
                                Icon="PageExcel"
                                Padding="5">
                                <DirectEvents>
                                    <Click OnEvent="ExportDataToExcel">
                                        <EventMask ShowMask="true" Msg="Exporting..."></EventMask>                                           
                                    </Click>
                                </DirectEvents>
                            </ext:Button>

在我的C#代码中,它是这样的:

private void CreateExcelFile(JournalEventItemDto[] data)
    {
        var tempFolderPath = Path.GetTempPath();
        var filePath = tempFolderPath + "export.xlsx";

        FileInfo newFile = new FileInfo(filePath);
        if (newFile.Exists)
        {
            try
            {
                newFile.Delete();
                newFile = new FileInfo(filePath);
            }
            catch (IOException)
            {
                X.Msg.Alert("Error!", "File is opened in another program").Show();
                return;
            }
        }

        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            var workSheet = package.Workbook.Worksheets.Add("Export");

            DataTable dataTable = new DataTable { Locale = CultureInfo.CurrentCulture };

            dataTable.Columns.Add("FullName", typeof(string));
            dataTable.Columns.Add("GuestName", typeof(string));
            dataTable.Columns.Add("Email", typeof(string));
            dataTable.Columns.Add("Date", typeof(string));
            dataTable.Columns.Add("Event", typeof(string));
            dataTable.Columns.Add("Page", typeof(string));
            dataTable.Columns.Add("Type", typeof(string));

            foreach (var item in data)
            {
                dataTable.Rows.Add(item.UserFullName, item.GuestName, item.Email,
                    item.EventDate.ToString("dd.MM.yyyy HH:mm:ss"), item.EventTypeText, item.EventPlaceText, item.ObjectTypeText);
            }

            workSheet.Cells["A1"].LoadFromDataTable(dataTable, true);
            workSheet.Cells.AutoFitColumns(0);
            package.Save();                                               
        }

        X.Msg.Alert("", "Successful export in " + filePath).Show();
    }
}

在这里,我只是将此文件保存在服务器端。

但是当我尝试像这样下载这个文件时:

Response.BinaryWrite(package.GetAsByteArray());
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=export.xlsx");

我收到错误。我想,这个问题出现在ext.net事件中。有人可以帮帮我吗?

Awfull error

1 个答案:

答案 0 :(得分:1)

奥克......解决方案很简单 - Why is the file not downloading?

正如我们所看到的,我们只需要在我们的aspx文件事件IsUpload =“true”中添加一个标志。