如何在ASP.Net(C#)WEB应用程序中实现将背景数据或线程导出到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)
{
}
//使用ClosedXML导出到Excel
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();
}
}
}
答案 0 :(得分:-1)
如果您要启动新的单线程,那么它将很有用。
var worker = new BackgroundWorker();
worker.DoWork += (o, ea) =>
{
//It will execute after start new Thread.
//Write your code for execute Export Excel.
};
worker.RunWorkerCompleted += (o, ea) =>
{
//You will get pointer when this worker finished the job.
};
worker.RunWorkerAsync();