使用asp.net和vb.net从sql server导出到excel文件?

前端之家收集整理的这篇文章主要介绍了使用asp.net和vb.net从sql server导出到excel文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法直接使用asp.net和vb.net从sql server 2008导出一个表中的整个数据而不使用datagridview到EXCEL FILE?

解决方法

基本上,您只需要遍历DataTable的列和行,以便将它们输出到响应中. This link告诉你如何.

在C#中:

DataTable dt = GetData();
        string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition",attachment);
        Response.ContentType = "application/vnd.ms-excel";
        string tab = "";
        foreach (DataColumn dc in dt.Columns)
        {
            Response.Write(tab + dc.ColumnName);
            tab = "\t";
        }
        Response.Write("\n");

        int i;
        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            for (i = 0; i < dt.Columns.Count; i++)
            {
                Response.Write(tab + dr[i].ToString());
                tab = "\t";
            }
            Response.Write("\n");
        }
        Response.End();

在VB.NET中

Dim dt As DataTable = GetData()
    Dim attachment As String = "attachment; filename=Employee.xls"
    Response.ClearContent()
    Response.AddHeader("content-disposition",attachment)
    Response.ContentType = "application/vnd.ms-excel"
    Dim tab As String = ""
    For Each dc As DataColumn In dt.Columns
        Response.Write(tab + dc.ColumnName)
        tab = vbTab
    Next
    Response.Write(vbLf)

    Dim i As Integer
    For Each dr As DataRow In dt.Rows
        tab = ""
        For i = 0 To dt.Columns.Count - 1
            Response.Write(tab & dr(i).ToString())
            tab = vbTab
        Next
        Response.Write(vbLf)
    Next
    Response.End()
原文链接:https://www.f2er.com/aspnet/251844.html

猜你在找的asp.Net相关文章