在vb.net中将数据导出为ex​​cel

时间:2011-09-28 21:22:24

标签: asp.net vb.net export-to-excel

我无法将数据导出到Excel中 我已经尝试了关于S / O的建议,但没有运气。

        Dim sqlString As String = "spExportRateProfile" & Session("OfficeNumber") & "," & Session("SalesRepID")
        Dim conn As SqlConnection = New SqlConnection(Utils.GetConfigKey("ConnectionStringVimas"))
        conn.Open()
        Dim dt As DataTable = New DataTable()
        Dim da As SqlDataAdapter = New SqlDataAdapter(sqlString, conn)
        da.Fill(dt)

        Response.AddHeader("content-disposition", "attachment;filename=ReportExport.xlsx")
        Response.ContentType = "application/vnd.ms-excel"  

在将此数据导出到Excel后,我需要做什么?

3 个答案:

答案 0 :(得分:1)

您可以使用像EPPlus(GPL)这样的Excel图库,我可以热烈推荐。

然后从DataTable创建Excel文件并将其写入响应就这么简单:

Dim pck = New ExcelPackage()
Dim ws = pck.Workbook.Worksheets.Add("Worksheet-Name")
ws.Cells("A1").LoadFromDataTable(dt, True, OfficeOpenXml.Table.TableStyles.Medium1)
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;  filename=ExcelFileName.xlsx")
Response.BinaryWrite(pck.GetAsByteArray())

这是另一个例子:http://epplus.codeplex.com/wikipage?title=WebapplicationExample

答案 1 :(得分:0)

一旦你有了数据表dt,你应该这样做(C# - 只是从互联网上复制)

...
da.Fill(dt);

Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"test.csv\"");
Response.Write((new ExportXMLCSV()).ToCSV(dt));
Response.End();

这里是ToCSV类的方法ExportXMLCSV(C# - 刚从互联网上复制过来)

public string ToCSV(DataTable dataTable)
    {
        //create the stringbuilder that would hold our data
        StringBuilder sb = new StringBuilder();
        //check if there are columns in our datatable
        if (dataTable.Columns.Count != 0)
        {
            //loop thru each of the columns so that we could build the headers
            //for each field in our datatable
            foreach (DataColumn column in dataTable.Columns)
            {
                //append the column name followed by our separator
                sb.Append(column.ColumnName + ',');
            }
            //append a carriage return
            sb.Append("\r\n");
            //loop thru each row of our datatable
            foreach (DataRow row in dataTable.Rows)
            {
                //loop thru each column in our datatable
                foreach (DataColumn column in dataTable.Columns)
                {
                    //get the value for tht row on the specified column
                    // and append our separator
                    sb.Append(row[column].ToString() + ',');
                }
                //append a carriage return
                sb.Append("\r\n");
            }
        }
        //return our values
        return sb.ToString();
    }

从这里复制的所有内容:http://forums.asp.net/t/1115305.aspx你应该很好地进行一些转换C# - > VB.NET; - )

答案 2 :(得分:0)