2011-09-28 141 views
1

我无法将我的数据导出到excel中。
我已经尝试了关于S/O的建议,但一直没有任何运气。将数据导出到excel中vb.net

 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之后,我需要做什么?

+0

使用ExcelLibrary尝试此链接:http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c – Csharp

回答

1

你可以使用我可以推荐的EPPlus(GPL)这样的ExcelLibrary。

然后,它是那么容易,因为这从一个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

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(); 

和类ExportXMLCSV这里的方法ToCSV(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 ;-)