asp.net导出excel和打印指定内容的简单代码
导出Excel:
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.table.RenderControl(hw);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
Page.EnableViewState = false;
string fileName = DateTime.Now+ ".xls";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
//关键代码如下:
Response.Write("<html xmlns:x='urn:schemas-microsoft-com:office:excel'><head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + fileName + "</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo /> </x:Print> </x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\"><title> Copyright by SDU</title></head><body><center>");
Response.Write(sw.ToString());
Response.Write("</center></body></html>");
Response.End();
打印指定内容: