ASP.NETがExcelにエクスポートされたときに改行されたコードを保持

3743 ワード

完全なコード:


<br>protected void Button1_Click(object sender, EventArgs e) <br>{ <br>System.Web.HttpContext curContext = System.Web.HttpContext.Current; <br>// IO excel <br>System.IO.StringWriter strWriter = null; <br>System.Web.UI.HtmlTextWriter htmlWriter = null; <br>// <br>HttpContext.Current.Response.Clear(); <br>HttpContext.Current.Response.Buffer = true; <br>HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "aaa.xls")); <br>curContext.Response.ContentType = "application/vnd.ms-excel"; <br>curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB18030"); <br>curContext.Response.Charset = ""; <br>// excel <br>strWriter = new System.IO.StringWriter(); <br>htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); <br>htmlWriter.WriteLine(" "); <br>// <br>GridView1.RenderControl(htmlWriter); <br>curContext.Response.Write(strWriter.ToString().Replace("<br/>", "<br style='mso-data-placement:same-cell;'/> ")); <br>curContext.Response.End(); <br>} <br>protected void Page_Load(object sender, EventArgs e) <br>{ <br>if (!Page.IsPostBack) <br>{ <br>GridView1.DataSource = CreateDataSourceByXianhuiMeng(); <br>GridView1.DataBind(); <br>} <br>} <br>System.Data.DataView CreateDataSourceByXianhuiMeng() <br>{ <br>System.Data.DataTable dt = new System.Data.DataTable(); <br>System.Data.DataRow dr; <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.String))); <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.String))); <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.Decimal))); <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.Decimal))); <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.Decimal))); <br>dt.Columns.Add(new System.Data.DataColumn(" ", typeof(System.Decimal))); <br>for (int i = 0; i < 8; i++) <br>{ <br>System.Random rd = new System.Random(Environment.TickCount * i); ; <br>dr = dt.NewRow(); <br>dr[0] = " " + i.ToString(); <br>dr[1] = " : E " + i.ToString() + "<br/> :" + " " + i.ToString(); <br>dr[2] = System.Math.Round(rd.NextDouble() * 100, 2); <br>dr[3] = System.Math.Round(rd.NextDouble() * 100, 2); <br>dr[4] = System.Math.Round(rd.NextDouble() * 100, 2); <br>dr[5] = System.Math.Round(rd.NextDouble() * 100, 2); <br>dt.Rows.Add(dr); <br>} <br>System.Data.DataView dv = new System.Data.DataView(dt); <br>return dv; <br>} <br>public override void VerifyRenderingInServerForm(Control control) <br>{ } <br>
















Excelで使用されているスタイル仕様を参照するには、「Microsoft」を参照してください.® Office HTML and XML Reference.ダウンロード先:http://download.microsoft.com/download/a/c/1/ac18e8a2-ce20-41b5-8407-c4cec4a17f19/ofhtml9.exe