SQL数据库到Excel [英] Sql database to Excel

查看:77
本文介绍了SQL数据库到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Sql Server 2007数据库中有一些表,我需要通过在dropdownlist中选择表名来将表的内容复制到excel工作表中. C#code.plz帮助我.....

I have some tables in my Sql server 2007 database I need to copy the contents of the table into an excel sheet by selecting the table name in a dropdownlist.with an event or method through the front end in the asp.net using C# code.plz help me.....

推荐答案

请参阅以下链接.这可能对实现您想要的有用.

从C#.Net中的Datatable导出到EXCEL [ ^ ]
Refer to the following link. this could be useful to achieve what you want.

Export to EXCEL from Datatable in C#.Net[^]


希望您在这里得到答案 ^ ]
I hope you get the answer here Export GridView Data to Excel using OpenXml[^]


好吧,尝试一下.这是将数据表导出到excel的完整源代码

Well, try this. Here is the full source to export datatable to excel

public void ExportToExcel(DataTable data, string fileName)
{
    HttpContext context = HttpContext.Current;
    context.Response.Clear();

    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

    //iterate column header names
    for (int i = 0; i < data.Columns.Count; i++)
    {
        if (i > 0)
        {
            context.Response.Write(",");
        }
        context.Response.Write(data.Columns[i].ColumnName);
    }
    context.Response.Write(Environment.NewLine);

    //prepare data
    foreach (DataRow row in data.Rows)
    {

        for (int i = 0; i < data.Columns.Count; i++)
        {
            if (i > 0)
            {
                context.Response.Write(",");
            }
            context.Response.Write(row.ItemArray[i].ToString());
        }
        context.Response.Write(Environment.NewLine);
    }
    context.Response.End();
}

private DataTable getData()
{
    //return datatable - that you get from database
}

protected void Button1_Click(object sender, EventArgs e)
{
    ExportToExcel(getData(), "[customefilename]");
}



希望这会有所帮助.
欢呼



Hope this helps.
cheers


这篇关于SQL数据库到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆