ASP.NET 2.0匯出到Excel時保留換行的方法

iDotNetSpace發表於2009-01-05

由於Excel畢竟不是 HTML,它有自己的樣式標準,在Excel 中,實現換行的方法是:



完整程式碼:

  protected void Button1_Click(object sender, EventArgs e)
  {
    System.Web.HttpContext curContext = System.Web.HttpContext.Current;
    // IO用於匯出並返回excel檔案 
    System.IO.StringWriter strWriter = null;
    System.Web.UI.HtmlTextWriter htmlWriter = null;

    // 設定編碼和附件格式 
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "aaa.xls"));

    curContext.Response.ContentType = "application/vnd.ms-excel";
    curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB18030");
    curContext.Response.Charset = "";

    // 匯出excel檔案 
    strWriter = new System.IO.StringWriter();
    htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
    htmlWriter.WriteLine("標題");

    // 返回客戶端 
    GridView1.RenderControl(htmlWriter);
    curContext.Response.Write(strWriter.ToString().Replace("
", "
"));
    curContext.Response.End();
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      GridView1.DataSource = CreateDataSourceByXianhuiMeng();
      GridView1.DataBind();
    }
  }

  System.Data.DataView CreateDataSourceByXianhuiMeng()
  {
    System.Data.DataTable dt = new System.Data.DataTable();
    System.Data.DataRow dr;
    dt.Columns.Add(new System.Data.DataColumn("學生班級", typeof(System.String)));
    dt.Columns.Add(new System.Data.DataColumn("學生姓名", typeof(System.String)));
    dt.Columns.Add(new System.Data.DataColumn("語文", typeof(System.Decimal)));
    dt.Columns.Add(new System.Data.DataColumn("數學", typeof(System.Decimal)));
    dt.Columns.Add(new System.Data.DataColumn("英語", typeof(System.Decimal)));
    dt.Columns.Add(new System.Data.DataColumn("計算機", typeof(System.Decimal)));

    for (int i = 0; i < 8; i++)
    {
      System.Random rd = new System.Random(Environment.TickCount * i); ;
      dr = dt.NewRow();
      dr[0] = "班級" + i.ToString();
      dr[1] = "學生姓名:孟子E章" + i.ToString() + "
所在班級:" + "班級" + i.ToString();
      dr[2] = System.Math.Round(rd.NextDouble() * 100, 2);
      dr[3] = System.Math.Round(rd.NextDouble() * 100, 2);
      dr[4] = System.Math.Round(rd.NextDouble() * 100, 2);
      dr[5] = System.Math.Round(rd.NextDouble() * 100, 2);
      dt.Rows.Add(dr);
    }
    System.Data.DataView dv = new System.Data.DataView(dt);
    return dv;
  }
  public override void VerifyRenderingInServerForm(Control control)
  { }



  無標題頁


 
 
   
     
   

 

 
 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-526827/,如需轉載,請註明出處,否則將追究法律責任。

相關文章