using System.Data;
using System.web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
namespace DotNet.Utilities
{
///
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
//HttpContext.Current.Response.Charset = "utf-8";
using (StringWriter sw = new StringWriter())
{
using (htmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
table.GridLines = GridLines.Both; //单元格之间添加实线
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
///
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
///
StringBuilder s = new StringBuilder();
s.Append("
int count = grid.Columns.Count;
s.Append("");
if (grid.Columns[i].GetType() == typeof(BoundField))
s.Append("" + grid.Columns[i].HeaderText + "");
//s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");
}
s.Append("");
foreach (DataRow dr in dt.Rows)
{
s.AppendLine("");
for (int n = 0; n < count; n++)
{
if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))
s.Append("" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "");
}
s.AppendLine("");
}
s.Append("");
s.Append("");
page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));
page.Response.End();
}
}
}
来源: http://www.bubuko.com/infodetail-1995223.html