Datatable或Gridview中的数据导出为excel表格数据(Asp.net C#)

1//注意引入IO空间
 using System.IO;
 


2(1)在源代码<page>里中加入:EnableEventValidation = "false" 
 (2) public void ExcelOut(GridView gv)
    {//导出Excel表的方法
        if (gv.Rows.Count > 0)
        {//有数据行
            Response.Clear();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition","attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//以系统时间设置为文件名
            Response.ContentEncoding = System.Text.Encoding.UTF8;//UTF8编码
            Response.ContentType = "application/ms-excel";//文件类型
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();//结束
        }
        else
        {
           Response.Write("没有数据记录");
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {//导出按钮事件
        ExcelOut(GridView1);//调用方法
    }
    public override void VerifyRenderingInServerForm(Control control)//必须有这个方法(就是个空方法)
    {    }
 
第二种方式以Datatable为数据源导出
 /// <summary>
        /// datatable数据源导出excel表
        /// </summary>
        /// <param name="dt">datatable数据源</param>
        /// <param name="zprice">合计(其实只要dt即可)</param>
        /// <param name="title">表头</param>
        public void ExcelOutTest(DataTable dt,string zprice,string title)
        {//导出Excel表的方法
            StringWriter sw = new StringWriter();
            sw.WriteLine("烟草公司"+title+"耗材领用表");
            sw.WriteLine("商品名称,出库日期,出库数量,单价,小计");//标题    
            foreach (DataRow dr in dt.Rows)         
            {//字段名   
                sw.WriteLine(dr["name"].ToString() + "," + dr["odate"].ToString() + "," + dr["onum"].ToString() + "," + dr["dprice"].ToString() + "," + dr["zj"].ToString());  
              
            }
            sw.WriteLine("合计,,,,"+zprice);//标题  
            sw.Close();
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";//以当前时间为excel表命名    
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));   
            Response.ContentType = "vnd.ms-excel.numberformat:yyyy-MM-dd ";    
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");         
            Response.Write(sw);      
            Response.End();
        }   
导出按钮:
  protected void BtnOutexcel_Click(object sender, EventArgs e)
        {
            OutKu outku = new OutKu();
            string operson, stime, etime;
            operson = "";
            if (!string.IsNullOrEmpty(TbStime.Text))
            {
                stime = TbStime.Text;
            }
            else
            {
                stime = "";
            }
            if (!string.IsNullOrEmpty(TbEtime.Text))
            {
                etime = TbEtime.Text;
            }
            else
            {
                etime = "";
            }
            string state = "已通过";
            DataTable dt = outku.Sel_OutKuByPerson(operson, state, stime, etime);
            string s = "1,1,1,1,100,333,666,,1";
            object[] parm = s.Split(',');
            dt.Rows.Add(parm);//添加一行
            string zprice = dt.Compute("sum(zj)", "").ToString();
            ExcelOutTest(dt, zprice, LbTitle.Text);           
        }

/// <summary>
/// 将DataTable数据导出到EXCEL,调用该方法后自动返回可下载的文件流
/// </summary>
/// <param name="dtData">要导出的数据源</param>
public static void DataTable1Excel(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();
}
}

 


/// <summary>
/// 直接输出Excel
/// </summary>
/// <param name="dtData"></param>
public static void DataTable2Excel(System.Data.DataTable dtData)
    {
  System.Web.UI.WebControls.DataGrid dgExport = 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.UTF8;
        curContext.Response.Charset = "";

        // 导出excel文件
        strWriter = new System.IO.StringWriter();
        htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

        // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
        dgExport = new System.Web.UI.WebControls.DataGrid();
        dgExport.DataSource = dtData.DefaultView;
        dgExport.AllowPaging = false;
        dgExport.DataBind();

        // 返回客户端
        dgExport.RenderControl(htmlWriter);  
        curContext.Response.Write(strWriter.ToString());
        curContext.Response.End();
      }
    }

 

/// <summary>
/// dtData是要导出为Excel的DataTable,FileName是要导出的Excel文件名(不加.xls)
/// </summary>
/// <param name="dtData"></param>
/// <param name="FileName"></param>
private void DataTable3Excel(System.Data.DataTable dtData, String FileName)
{
System.Web.UI.WebControls.GridView dgExport = 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)
{
//设置编码和附件格式
//System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312";

//导出Excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

//为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
dgExport = new System.Web.UI.WebControls.GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();

//下载到客户端
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}

/// <summary>
/// Datatable to Excel带自定文件名的导出
/// </summary>
/// <param name="dt"></param>
/// <param name="FileName"></param>
private void DataTable4Excel(System.Data.DataTable dt, string FileName)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
//System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
//System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();
//AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.Font.Bold = true;
headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
//itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; ;

//excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
excel.HeaderStyle.MergeWith(headerStyle);
//excel.ItemStyle.MergeWith(itemStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = true;
excel.DataSource = dt.DefaultView; //输出DataTable的内容
excel.DataBind();

//for (int i = 0; i < excel.Items.Count; i++)
//{
// //excel.Columns[3].ItemStyle.CssClass = "xlsText";
// //excel.Items[i].Cells[3].Style.Add("mso-number-format", "\"@\"");
// for (int j = 0; j < aColTxtFormat.Length; j++)
// {
// int nCol = aColTxtFormat[j];
// excel.Items[i].Cells[nCol].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
// }
//}
excel.RenderControl(htmlWriter);

HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename='"+FileName+".xls'");
//HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
//HttpContext.Current.Response.ContentType=".xls/.txt/.doc";image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
HttpContext.Current.Response.ContentType = ".xls";
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值