程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> NET頁面導出Excel實例代碼

NET頁面導出Excel實例代碼

編輯:ASP.NET基礎

復制代碼 代碼如下:
public static void CreateExcel(DataSet ds)
        {
            string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
            string colHeaders = "", ls_item = "";

            //定義表對象與行對象,同時用DataSet對其值進行初始化
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以類似dt.Select("id>10")之形式達到數據篩選目的
            int i = 0;
            int cl = dt.Columns.Count;


            //取得數據表各列標題,各標題之間以\t分割,最後一個列標題後加回車符
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最後一列,加\n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }

            }
            HttpContext.Current.Response.Write(colHeaders);
            //向HTTP輸出流中寫入取得的數據信息

            //逐行處理數據 
            foreach (DataRow row in myRow)
            {
                //當前行數據寫入HTTP輸出流,並且置空ls_item以便下行數據   
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最後一列,加\n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                HttpContext.Current.Response.Write(ls_item);
                ls_item = "";

            }
            HttpContext.Current.Response.End();
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved