private void load() { DataSet ds = getDataset(); string FileName = "excel"; //Web頁(yè)面定義 //System.Web.UI.Page mypage=new System.Web.UI.Page(); HttpResponse resp; resp = HttpContext.Current.Response; resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.AppendHeader("Content-disposition", "attachment;filename=" + FileName + ".xls"); resp.ContentType = "application/octet-stream";//默認(rèn) //resp.ContentType = "application/x-xls"; //變量定義 string colHeaders = null; string Is_item = null; //顯示格式定義//////////////// //文件流操作定義 // FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write); //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312")); StringWriter sfw = new StringWriter(); //定義表對(duì)象與行對(duì)象,,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 System.Data.DataTable dt = ds.Tables[0]; DataRow[] myRow = dt.Select(); int i = 0; int cl = dt.Columns.Count; //取得數(shù)據(jù)表各列標(biāo)題,,各標(biāo)題之間以\t分割,最后一個(gè)列標(biāo)題后加回車符 for (i = 0; i < cl; i++) { //if(i==(cl-1)) //最后一列,,加\n // colHeaders+=dt.Columns[i].Caption.ToString(); //else colHeaders += dt.Columns[i].Caption.ToString() + "\t"; } sfw.WriteLine(colHeaders); //sw.WriteLine(colHeaders); //逐行處理數(shù)據(jù) foreach (DataRow row in myRow) { //當(dāng)前數(shù)據(jù)寫入 for (i = 0; i < cl; i++) { //if(i==(cl-1)) // Is_item+=row[i].ToString()+"\n"; //else Is_item += row[i].ToString() + "\t"; } sfw.WriteLine(Is_item); //sw.WriteLine(Is_item); Is_item = null; } resp.Write(sfw); //resp.Clear(); resp.End(); } private DataSet getDataset() { string sql = "SELECT * FROM 成績(jī)表"; SqlConnection conn = new SqlConnection("server=.;database=DB;uid=sa;password=123;"); conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(); ad.SelectCommand = cmd; ad.Fill(ds, "成績(jī)表"); return ds; } } |
|
來(lái)自: XXG學(xué)習(xí)園 > 《Asp.net》