南京北大青鸟

全国咨询电话:15195455103

三分钟了解北大青鸟
当前位置:南京北大青鸟 > 学习园地 > 编程技巧

非常实用的.Net导出Excel源码

来源:南京北大青鸟      作者:刘胜      发布时间:2013-06-05 14:39:32

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
 
namespace ZOA
{
    public class ExportExcel
    {
        public ExportExcel()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
 
        public  void ToExcel(DataTable p_Table, HttpResponse p_Response, string p_Title)
        {
            int _CountR = p_Table.Rows.Count;//行数
            int _CountC = p_Table.Columns.Count;//列数
            p_Response.Clear();
            p_Response.Buffer = true;
 
            //设置Http的头信息,编码格式
            p_Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(p_Title) + ".xls");
            p_Response.ContentType = "application/ms-excel";
 
            //设置编码
            p_Response.Charset = "GB2312";
            p_Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
 
            //写表头
            for (int i = 0; i < _CountC; i++)
            {
                p_Response.Write(p_Table.Columns[i].ColumnName + "\t");
            }
            p_Response.Write("\n");
 
            //写表内容
            for (int RowNo = 0; RowNo <= _CountR - 1; RowNo++)
            {
                string RowContent = "";
                string _Content = string.Empty;
                for (int CloumnNo = 0; CloumnNo <= _CountC - 1; CloumnNo++)
                {
                    _Content = Convert.ToString(p_Table.Rows[RowNo][CloumnNo]);
                    if (_Content == "1900-1-1 0:00:00")
                    {
                        _Content = "";
                    }
                    if (_Content.Contains("\n") == true)
                    {
                        _Content = _Content.Replace("\n", "");
                    }
                    if (_Content.Contains("\r") == true)
                    {
                        _Content = _Content.Replace("\r", "");
                    }
                    if (_Content.Contains("\t") == true)
                    {
                        _Content = _Content.Replace("\t", "");
                    }
 
                    RowContent += _Content + " \t";
                }
                RowContent += "\n";
                p_Response.Write(RowContent);
            }
            p_Response.End();
        }
    }
}
 
这是一个类,调用方法如下:
 
 
//导出数据
    protected void BExportData_Click(object sender, EventArgs e)
    {
        ExportExcel ee = new ExportExcel();
        DataTable dt = QueryMain();
        //更改列名
        dt.Columns["workid"].ColumnName = "编号";
        dt.Columns["userid"].ColumnName = "工号";
        dt.Columns["username"].ColumnName = "姓名";
        dt.Columns["dept"].ColumnName = "部门";
        dt.Columns["position"].ColumnName = "职位";
 
        ee.ToExcel(dt, Response, "Report");
    }

分享到:

相关阅读:

近期文章

抢试听名额

名额仅剩66名

教育改变生活

WE CHANGE LIVES