上午給系統的訂單管理部分添加了一個功能,把查詢到的訂單信息導出到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處理狀態\t\n";
// 向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"].T
oString() + "\t";
strExcelItems += reader["IsValid"].ToString() + "\t";
strExcelItems += reader["DealState"].ToString() +"\n";
Response.Write(strExcelItems);
}
reader.Close();
Response.End();
}
我這裡只是簡單的把查詢到的數據以Excel的形式Write出來(當然也可以是其他格式,比如XML),對簡單的需求足矣了,當然,用.Net直接去操作Excel文件也是很簡單的,有很多這樣的例子可以參考。