ASP.NET导出excel公共类

公共类 ToExcel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;

/// <summary>
///ToExcel 导出excel
/// </summary>
public class ToExcel
{
 public ToExcel()
 {
 }

    public void ExcelExport(StringWriter sw, string exportFileName)
    {
        System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        //避免文件名称乱码
        string fileName = HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.UTF8);
        string str = "attachment;filename=" + fileName + ".xls";

        System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", str);
        System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
        System.Web.HttpContext.Current.Response.Write(sw);
        System.Web.HttpContext.Current.Response.End();
    }

    public static StringWriter GetStringWriter(string[] sz, DataTable dt)
    {
        StringWriter sw = new StringWriter();
        //先写列表头
        for (int i = 0; i < sz.Length; i++)
        {
            sw.Write(sz[i] + "/t");
        }
        sw.Write(sw.NewLine);

        //数据
        if (dt != null)
        {
            //写数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count ; j++)
                {
                    sw.Write(dt.Rows[i][j].ToString() + "/t" );
                }
               sw.Write(sw.NewLine);  
            }
        }
        sw.Close();
        return sw;
    }
}

 

前台导出excel按钮 的事件

protected void btnExcel_Click(object sender, EventArgs e)
    {

//excel表头数据
        string[] strRange = new string[3];
        strRange[0] = "客户编号";
        strRange[1] = "物料号";
        strRange[2] = "购买时间";

//excel表体数据

        DataSet ds = DA_PromotionalOrder.GetSuccess(tj);
        DataTable dt = ds.Tables[0];
        ToExcel excel = new ToExcel();
        StringWriter sw1 = ToExcel.GetStringWriter(strRange, dt);
        excel.ExcelExport(sw1, "记录");
    }

这种方式有个缺点,就是如果你往excel中插入的数据是以数字0开头,如:“0012121”,那么插入excel后是“12121”,当然我们也可以把StringWriter()方法与ExcelExport()方法添加到前台中,就不用写ToExcel.cs文件了

转载地址:http://hi.baidu.com/supermeizhiyun/blog/item/46dcdc4e77ba67ebd72afc8b.html

 

这篇文章写得很实用,做普通报表可以用 此方法,复杂报表。另作修改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值