以下是导出方法:
1 public static void Export(string fileName, SPGridView gv) 2 { 3 4 HttpContext.Current.Response.Clear(); 5 HttpContext.Current.Response.Buffer = true; 6 HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>"); 7 HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 8 HttpContext.Current.Response.AddHeader( 9 "content-disposition", string.Format("attachment; filename={0}", fileName.Replace(" ","_"))); 10 HttpContext.Current.Response.Charset = "UTF-8"; 11 HttpContext.Current.Response.HeaderEncoding = Encoding.UTF8; 12 HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; 13 14 using (StringWriter sw = new StringWriter()) 15 { 16 using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 17 { 18 Table table = new Table(); 19 20 gv.HeaderRow.Cells[0].Visible = false; 21 gv.FooterRow.Cells[0].Visible = false; 22 23 if (gv.HeaderRow != null) 24 { 25 GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); 26 table.Rows.Add(gv.HeaderRow); 27 } 28 29 foreach (GridViewRow row in gv.Rows) 30 { 31 GridViewExportUtil.PrepareControlForExport(row); 32 row.Cells[0].Visible = false; 33 table.Rows.Add(row); 34 } 35 36 if (gv.FooterRow != null) 37 { 38 GridViewExportUtil.PrepareControlForExport(gv.FooterRow); 39 table.Rows.Add(gv.FooterRow); 40 } 41 42 table.RenderControl(htw); 43 44 HttpContext.Current.Response.Write(sw.ToString()); 45 HttpContext.Current.Response.End(); 46 } 47 } 48 } 49 50 private static void PrepareControlForExport(Control control) 51 { 52 for (int i = 0; i < control.Controls.Count; i++) 53 { 54 Control current = control.Controls[i]; 55 if (current is LinkButton && current.Visible) 56 { 57 control.Controls.Remove(current); 58 control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 59 } 60 else if (current is HyperLink && current.Visible) 61 { 62 control.Controls.Remove(current); 63 control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 64 } 65 else if (current.Visible == false) 66 { 67 control.Controls.Remove(current); 68 } 69 70 if (current.HasControls()) 71 { 72 GridViewExportUtil.PrepareControlForExport(current); 73 } 74 } 75 }