本文實例講述了asp.net中一些常用的excel數據導出方法,同時也介紹了在數據導入或導出時可能碰到的一些問題總結,。希望文章對你會有所幫助。具體實現方法如下:
1、由dataset生成
代碼如下:public void CreateExcel(DataSet ds,string typeid,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
string colHeaders= "", ls_item="";
int i=0;
//定義表對象與行對像,同時用DataSet對其值進行初始化
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select("");
// typeid=="1"時導出為EXCEL格式文件;typeid=="2"時導出為XML格式文件
if(typeid=="1")
{
//取得數據表各列標題,各標題之間以t分割,最后一個列標題后加回車符
for(i=0;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 ls_item +=row[i].ToString() + "t";
ls_item += row[i].ToString() +"n";
//當前行數據寫入HTTP輸出流,并且置空ls_item以便下行數據
resp.Write(ls_item);
ls_item="";
}
}
else
{
if(typeid=="2")
{
//從DataSet中直接導出XML數據并且寫到HTTP輸出流中
resp.Write(ds.GetXml());
}
}
//寫緩沖區中的數據到HTTP頭文件中
resp.End();
}
2、由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";
新聞熱點
疑難解答
圖片精選