上午為系統的訂單管理部分新增了一個功能,把查詢到的訂單資訊匯出到Excel,供管理員分析用。以前寫的程式碼如下:
Response.Clear();
Response.BufferOutput = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename = FileName.xls");
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.Globalization.CultureInfo myinfo = new System.Globalization.CultureInfo("ZH-CN", true);
StringWriter osw = new StringWriter(myinfo);
HtmlTextWriter ohtw = new HtmlTextWriter(osw);
dgQueryResult.RenderControl(ohtw);
Response.Write(osw);
Response.End();
我的查詢用了分頁,客戶要求把所有查詢到的資料都匯出到Excel,所以不能像以前那樣透過把控制項的內容匯出到Excel來實現此功能,於是把程式碼改成這樣:
Response.Clear();
Response.BufferOutput = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename = 訂單.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
string strExcelHeader = string.Empty;
string strExcelItems;
if(ViewState["SQL"] != null) // 取前面查詢用的SQL語句
{
// 取得各列標題,各標題之間以t分割,最後一個列標題後加回車符
strExcelHeader = "訂單號碼t經銷商t地區t小類t商品t實付金額t下單時間t有效狀態t處理狀態tn";
// 寫入所向HTTP輸出流中所取得的資料資訊
Response.Write(strExcelHeader);
// 逐行處理查詢結果數據
ITDBHandle itDbHandle = new ITDBHandle();
itDbHandle.QueryString = ViewState["SQL"].ToString();
SqlDataReader reader = itDbHandle.ExecuteDataReader();
while(reader.Read())
{
strExcelItems = string.Empty;
strExcelItems += reader["OrderID"].ToString() + "t";
strExcelItems += reader["DealerName"].ToString() + "t";
strExcelItems += reader["City"].ToString() + "t";
strExcelItems += reader["SmallClassName"].ToString() + "t";
strExcelItems += reader["BrandName"].ToString() + reader["Model"].ToString() + "t";
strExcelItems += reader["TotalPrice"].ToString() + "t";
strExcelItems += reader["OrderDate"].ToString() + "t";
strExcelItems += reader["IsValid"].ToString() + "t";
strExcelItems += reader["DealState"].ToString() +"n";
Response.Write(strExcelItems);
}
reader.Close();
Response.End();
}
我這裡只是簡單的把查詢到的資料以Excel的形式Write出來(當然也可以是其他格式,例如XML),對簡單的需求足矣了,當然,用.NET直接去操作Excel檔案也是很簡單的,有很多這樣的例子可以參考。