2011-09-28 143 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 ;-)