Как реализовать backgroundworker или поток в веб-приложении ASP.Net (C #) для экспорта большого количества данных в Excel?Есть ли другой способ экспорта в Excel в фоновом режиме?
<%@ Page Title="" Language="C#" MasterPageFile="~/export_module.master"
AutoEventWireup="true" CodeFile="GenerateReport.aspx.cs"
Inherits="" Async="true" %>
public readonly BackgroundWorker worker = new BackgroundWorker();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(DoWork);
//worker.ProgressChanged += new ProgressChangedEventHandler(WorkerProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
}
}
// Экспорт в Excel Нажмите событие
protected void btn_Export_Click(object sender, EventArgs e)
{
if (!worker.IsBusy){
worker.RunWorkerAsync("ExportReport");
}
}
// BackgroundMethod
private void DoWork(object sender, DoWorkEventArgs e)
{
exportToExcel();
}
private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
// Экспорт в Excel с использованием ClosedXML
public void ExportReportWithHeaderClosedXML(string reportName, string fileName, DataTable dataTable)
{
int usedCells = dataTable.Columns.Count;
string ReportDate = string.Empty;
string attachment = "inline;filename=" + fileName + ".xlsx";
using (XLWorkbook wb = new XLWorkbook())
{
//Add method of ClosedXML class library only accepts worksheet name of 31 characters.
IXLWorksheet worksheet = wb.Worksheet(1);
//Insert Report Data
worksheet.Cell(4, 1).InsertTable(dataTable);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + fileName + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.End();
}
}
}