asp.net之gridview到datatable到excel
发布日期:2021-10-16 07:12:02 浏览次数:0 分类:技术文章

关于DataSet、DataTable、DataAdapt基础知识

步骤:
1.引入命名空间System.Data
2.创建DataSet对象
3.创建DataTable对象
4.将DataTable对象加入到DataSet对象中

using System.Data;DataSet ds=new DataSet("离职信息库");DataTable dt=new DataTable("离职信息表");ds.Table.Add(dt);

5.定义列,并向DataTable中已经定义好的列;

DataColumn dc1=new DataColumn("离职单位",Type.GetType("System.String"));DataColumn dc2=new DataColumn("姓名",Type.GetType("System.String"));dt.Columns.Add(dc1);dt.Columns.Add(dc2);


6.插入行数据
7.其他相关操作
http://blog.csdn.net/lishimin1012/article/details/38401459
http://blog.csdn.net/godbugs/article/details/51704566

以下代码并不是我写的,请参考原文(datagridview)。本人用gridview,为了方便,稍作修改,复制到这。

1.将gridview转换为DataTable

    public DataTable GetGvToTable(GridView gv)    {        DataTable dt = new DataTable();        for (int count = 0; count < gv.Columns.Count; count++)        {            DataColumn dc = new DataColumn(gv.Columns[count].HeaderText.ToString());            dt.Columns.Add(dc);        }        for (int count = 0; count < gv.Rows.Count; count++)        {            DataRow dr = dt.NewRow();            for (int countsub = 0; countsub < gv.Columns.Count; countsub++)            {                dr[countsub] = Convert.ToString(gv.Rows[count].Cells[countsub].Text);            }            dt.Rows.Add(dr);        }        return dt;    }

2.将DataTable导出并下载为EXCEL

 public void CreateExcel(DataTable dt, string FileType, string FileName)    {        Response.Clear();        Response.Charset = "UTF-8";        Response.Buffer = true;        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");        Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");        Response.ContentType = FileType;        string colHeaders = string.Empty;        string ls_item = string.Empty;        DataRow[] myRow = dt.Select();        int i = 0;        int cl = dt.Columns.Count;        foreach (DataRow row in myRow)        {            for (i = 0; i < cl; i++)            {                if (i == (cl - 1))                {                    ls_item += row[i].ToString() + "\n";                }                else                {                    ls_item += row[i].ToString() + "\t";                }            }            Response.Output.Write(ls_item);            ls_item = string.Empty;        }        Response.Output.Flush();        Response.End();    }

添加按钮,按钮单击事件代码。


    protected void btn_out_Click(object sender, EventArgs e)    {        DataTable ddat = GetGvToTable(gv1);        CreateExcel(ddat, "application/ms-excel",DateTime .Now .ToShortDateString() + "数据导出");    }




上一篇:C#学习笔记
下一篇:ASP.NET后台代码方式识别页面“按钮点击”和浏览器F5“刷新”事件