1。建两个datagrid,一个用来分页,另一个的visble设为false, 在剛開始加載時,將需要導出的DataGrid的Visble屬性設為false,在導出再設為true,导出时,就导出第二个,在导出後将visble高为true,导出后再设为false;关键代码见下:
protected void Button2_Click(object sender, System.EventArgs e)
{
Export();
//
}
private void Export()
{
Response.Charset ="GBK";
Response.ContentEncoding =System.Text .Encoding .UTF7 ;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMddhhmmss")+".xls");
Response.ContentType ="application/vnd.ms-excel";
this.EnableViewState =false;
StringWriter tw=new StringWriter();
HtmlTextWriter hw=new HtmlTextWriter (tw);
this.DataGrid2 .Visible =true;
this.DataGrid2 .RenderControl (hw);
Response.Write (tw);
Response.End ();
this.DataGrid2 .Visible =false;
}
导出xml格式的EXCEL(导出时建议导出没有分过页的数据):
tb=datasource;
if (tb.Count > decimal.Zero)
{
var sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\"?>");
sb.AppendLine("<?mso-application progid=\"Excel.Sheet\"?>");
sb.AppendLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
sb.AppendLine("<Styles>");
sb.AppendLine("<Style ss:ID=\"s62\">");
sb.AppendLine("<Borders />");
sb.AppendLine("<Alignment ss:WrapText=\"1\" ss:Vertical=\"Center\" ss:Horizontal=\"Center\" />");
sb.AppendLine("<NumberFormat ss:Format=\"@\" />");
sb.AppendLine("</Style>");
sb.AppendLine("<Style ss:ID=\"s17\">");
sb.AppendLine("<Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\"/>");
sb.AppendLine("</Style>");
sb.AppendLine("</Styles>");
sb.AppendLine("<Worksheet ss:Name=\"Sheet1\">");
sb.AppendLine("<Table>");
sb.AppendLine("<Row>");
sb.AppendLine("<Cell><Data ss:Type=\"String\">列名</Data></Cell>");
sb.AppendLine("</Row>");
if (tb != null)
{
foreach (var p in tb)
{
sb.AppendLine("<Row>");
sb.AppendLine("<Cell><Data ss:Type=\"String\">" + 数据+ "</Data></Cell>");
sb.AppendLine("</Row>");
}
}
sb.AppendLine("</Table>");
sb.AppendLine("</Worksheet>");
sb.AppendLine("</Workbook>");
var resp = HttpContext.Current.Response;
resp.ContentType = "application/vnd.ms-excel";
resp.AppendHeader("Content-Type", "application/vnd.ms-excel");
resp.AppendHeader("Content-Disposition", "attachment;filename=report.xls");
resp.Write(sb.ToString());
resp.End();
}