描述:最近在做一個工作流的項目,其中步驟中系統可以在每個月的十五號,三十號自動導出Excel。
附言:網上搜索到好多使用Timer並在global.asax文件中判斷並執行代碼的方便,我也那麼做了,結果還是不可以,這裡是否還有其他方法,請大家指教啦。
這是我在Global.asax文件中寫的,報錯了請指教一下
protected void Application_Start(object sender, EventArgs e)
{
#region 2014-11-10 每月十五號,三十號自動生成Excel文件
if (System.DateTime.Today.Equals(15) || System.DateTime.Today.Equals(30))
{
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.Enabled = true;
myTimer.AutoReset = true;
}
#endregion
}
#region 2014-11-10 每月十五號,三十號自動生成Excel文件
void myTimer_Elapsed(object source, ElapsedEventArgs e)
{
try
{
YourTask();
}
catch (Exception ee)
{
}
}
void YourTask()
{
System.Data.DataTable dtStatus = dbopimp.GetTodayDataExcel(System.DateTime.Now);
CreateExcel(dtStatus, System.DateTime.Now.ToShortDateString());
}
//導出Excel
public void CreateExcel(System.Data.DataTable dt, string FileName)
{
System.Data.DataTable dtname = dbopimp.GetAreaList();
for (int j = 0; j < dtname.Rows.Count; j++)
{
string areaname = dtname.Rows[0]["areaname"].ToString();
FileName = areaname + "當天數據" + FileName;
HttpResponse resp;
resp =Response;
resp.AppendHeader("Content-Disposition", "attachment;filename=Excel" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString() + ".xls");
resp.Charset = "UTF-8";
resp.ContentEncoding = System.Text.Encoding.Default;
resp.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
string colHeaders = "", ls_item = "";
int i = 0;
//定義表對象與行對像
DataRow[] myRow = dt.Select("");
resp.ContentType = "application/ms-excel";
//取得數據表各列標題,各標題之間以\t分割,最後一個列標題後加回車符
for (i = 0; i < dt.Columns.Count - 1; i++)
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
//向HTTP輸出流中寫入取得的數據信息
resp.Write(colHeaders);
//逐行處理數據
foreach (DataRow row in myRow)
{
//在當前行中,逐列獲得數據,數據之間以\t分割,結束時加回車符\n
for (i = 0; i < dt.Columns.Count - 1; i++)
{
ls_item += row[i].ToString() + "\t";
}
ls_item += row[i].ToString() + "\n";
//當前行數據寫入HTTP輸出流,並且置空ls_item以便下行數據
resp.Write(ls_item);
ls_item = "";
}
//寫緩沖區中的數據到HTTP頭文件中
resp.End();
}
}
//datagrid
public void ToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
雖然可以在asp.net中通過定時器處理一些任務,但是如果你工作量大,間隔時間長,建議還是放在專門的windows服務中處理。使用asp.net處理的弊端是:asp.net進程必須不斷請求激活,否則會因為休眠而回收,asp.net進程處理繁重的任務會干擾正常響應同時客戶端的請求,等等。