asp.net导出excel

来源:互联网 发布:最新mac pro安装win10 编辑:程序博客网 时间:2024/04/29 00:41

protected void DataTableToExcel(System.Data.DataTable dtData)
    {
        System.Web.UI.WebControls.GridView gvExport
= null;
       
// 当前对话
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
       
// IO用于导出并返回excel文件
        System.IO.StringWriter strWriter = null;
        System.Web.UI.HtmlTextWriter htmlWriter
= null;

       
if (dtData != null)
        {
           
// 设置编码和附件格式
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding
= System.Text.Encoding.GetEncoding("gb2312");
            curContext.Response.Charset
= "utf-8";

           
// 导出excel文件
            strWriter = new System.IO.StringWriter();
            htmlWriter
= new System.Web.UI.HtmlTextWriter(strWriter);
           
// 为了解决gvData中可能进行了分页的情况,需要重新定义一个无分页的GridView
            gvExport = new System.Web.UI.WebControls.GridView();
            gvExport.DataSource
= dtData.DefaultView;
            gvExport.AllowPaging
= false;
            gvExport.DataBind();

           
// 返回客户端
            gvExport.RenderControl(htmlWriter);
            curContext.Response.Write(
"<meta http-equiv=/"Content-Type/" content=/"text/html; charset=gb2312/" />" + strWriter.ToString());
            curContext.Response.End();
        }
    }

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls; public static class ToExcel
    {
       
//将GridView数据导出至Excel中

       
public static string GridViewToExcel(GridView gd, string strPath, string strFileName)
        {


           
new Help().CreateFolder(@"C:/reportforms");
                StringWriter sw
= new StringWriter();
                HtmlTextWriter htw
= new HtmlTextWriter(sw);
                gd.RenderControl(htw);
               
string strHtml = sw.ToString().Trim();
               
string ExcelFileName = strFileName;
               
string FilePhysicialPathName = strPath;      //Request.PhysicalApplicationPath;     

               
//生成的Excel文件名

               
string objectExcelFileName = Path.Combine(FilePhysicialPathName, ExcelFileName);
               
if (File.Exists(objectExcelFileName))
                {
                    File.Delete(objectExcelFileName);
                }
                FileStream fs
= new FileStream(objectExcelFileName, FileMode.Create);
                BinaryWriter bw
= new BinaryWriter(fs, Encoding.GetEncoding("GB18030"));
                bw.Write(strHtml);
                bw.Close();
                fs.Close();
               
return "";
           
         
        }
    }