如下是导出到TXT的方法
public static void ToTxt(DataTable dv, string FileName){System.IO.StringWriter sw = new System.IO.StringWriter();StringBuilder sb = new StringBuilder();//写标题for (int i = 0; i < dv.Columns.Count; i++){if (i > 0){sb.Append("\t ");}sb.Append(dv.Columns[i].ColumnName);}sw.WriteLine(sb.ToString());//写内容for (int rowNo = 0; rowNo < dv.Rows.Count; rowNo++){StringBuilder sbTemp = new StringBuilder();for (int columnNo = 0; columnNo < dv.Columns.Count; columnNo++){if (columnNo > 0){sbTemp.Append("\t ");}sbTemp.Append(dv.Rows[rowNo][columnNo].ToString());}sw.WriteLine(sbTemp.ToString());}System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;response.Clear();response.Buffer = true;response.ContentEncoding = System.Text.Encoding.Default;response.ContentType = "text/plan";response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".txt");response.Charset = "gb2312";response.Write(sw.ToString());response.End();sw.Close();}如下是导出到EXCEL的方法
/// <summary>/// Renders the html text before the datagrid./// </summary>/// <param name="writer">A HtmlTextWriter to write html to output stream</param>private static void FrontDecorator(HtmlTextWriter writer){writer.WriteFullBeginTag("HTML");writer.WriteFullBeginTag("Head");writer.WriteEndTag("Head");writer.WriteFullBeginTag("Body");}/// <summary>/// Renders the html text after the datagrid./// </summary>/// <param name="writer">A HtmlTextWriter to write html to output stream</param>private static void RearDecorator(HtmlTextWriter writer){writer.WriteEndTag("Body");writer.WriteEndTag("HTML");}public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel,string FileName,string Title, string Head){System.IO.StringWriter sw = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);FrontDecorator(hw);if ( Title != "")hw.Write(Title + "<br>");if ( Head != "")hw.Write(Head + "<br>");DataGrid2Excel.EnableViewState = false;DataGrid2Excel.RenderControl(hw);RearDecorator(hw);System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;response.Clear();response.Buffer = true;response.ContentEncoding = System.Text.Encoding.Default;response.ContentType ="application/Excel";response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");response.Charset = "gb2312";response.Write(sw.ToString());response.End();}