- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Text;
- using System.IO;
- //using System.Reflection;
- //using System.Runtime.InteropServices;
- //using Microsoft.Office.Tools.Excel;
- //using Microsoft.Office;
- /// <summary>
- /// OutPutExcel 的摘要说明
- /// </summary>
- public class OutPutExcel
- {
- public OutPutExcel()
- {
- //
- // TODO: 在此处添加构造函数逻辑
- //
- }
- /// <summary>
- /// 导出为Excel表格
- /// </summary>
- /// <param name="filename"></param>
- /// <param name="dg"></param>
- public static void OutExcel(string filename,DataGrid dg)
- {
- string strFileName =filename;
- System.IO.StringWriter SW = new System.IO.StringWriter();
- System.Web.UI.HtmlTextWriter HTW = new System.Web.UI.HtmlTextWriter(SW);
- //this.dg.AllowPaging = false;
- // GVDataBind();
- dg.RenderControl(HTW);
- //Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以
- System.Web.HttpContext.Current.Response.Buffer = true;
- System.Web.HttpContext.Current.Response.Clear();
- System.Web.HttpContext.Current.Response.ClearContent();
- System.Web.HttpContext.Current.Response.ClearHeaders();
- System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
- //Response.ContentType是输出流的 HTTP MIME 类型
- //Response.ContentType --- word文件
- //application/vnd.ms-excel --- excel文件
- //...
- System.Web.HttpContext.Current.Response.Charset = "gb2312";
- System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
- System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName + ".xls");
- //inline --- 在线打开
- //filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)
- //进行进行编码,以解决文件名乱码的问题
- System.Web.HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=/"text/html; charset=gb2312/">");
- System.Web.HttpContext.Current.Response.Write(SW.ToString());
- System.Web.HttpContext.Current.Response.Write("</body></html>");
- System.Web.HttpContext.Current.Response.Flush();
- System.Web.HttpContext.Current.Response.Close();
- }
- }
常用的代码堆积!一,导出excel
最新推荐文章于 2022-05-24 16:37:05 发布