2016-06-28 55 views
0

我想將數據添加到Excel文件,我建立了數據庫連接,並使用SSMS將需要的信息拖入存儲過程。使用VB.NET將特定數據庫數據添加到excel文件

我已經加入根據我的需要,一些行會在這裏的靜態數據的信息欄是我的代碼:

Private Sub ExcelOutput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelOutput.Click 


Dim xlApp As Excel.Application 
Dim xlWorkBook As Excel.Workbook 
Dim xlWorkSheet As Excel.Worksheet 
Dim xlRange As Excel.Range 
Dim misValue As Object = System.Reflection.Missing.Value 
Dim rNum As Random = New Random 



xlApp = New Excel.Application 
xlWorkBook = xlApp.Workbooks.Add(misValue) 
xlWorkSheet = xlWorkBook.Sheets("sheet1") 
xlRange = xlWorkSheet.UsedRange 


With xlWorkSheet 
    .Range("A1").Value = "Col1" 
    .Range("B1").Value = "Col2" 
    .Range("C1").Value = "Col3" 
    .Range("D1").Value = "Col4" 
    .Range("E1").Value = "Col5" 
    .Range("F1").Value = "Col6" 
    .Range("G1").Value = "Col7" 
    .Range("H1").Value = "Col8" 
    .Range("I1").Value = "Col9" 
    .Range("J1").Value = "Col10" 
    .Range("K1").Value = "Col11" 
    .Range("L1").Value = "Col12" 



    xlWorkSheet.Range("E2:E10").Value = DateTime.Now.ToString("dd-MMM-yy") 
     xlWorkSheet.Range("F2:F10").Value = "Upload" 
     xlWorkSheet.Range("G2:G10").Value = rNum.Next() 
     xlWorkSheet.Range("I2:I10").Value = "INCLUDED" 

End With 

我想知道的是如何我將能夠遍歷一個數據庫表,並根據每列中的信息填充Excel文件中的每個單元格,例如,col1將具有從存儲過程中提取的帳戶客戶ID。我想要使​​用循環將其放入Excel文件幷包含信息。

我是新來這個所以希望得到一些指導

回答

1

Let's use this as an example

比方說,我已經退出第二查詢到的DataTable。我會填充它導入到Excel與順序文件:A1是1660年,B1是HT5-088,A2是5882,等等....

下面的代碼:

Dim pos As String = "" 
    For i As Integer = 0 To datatable.Rows.Count - 1 'rows 
     For j As Integer = 0 To datatable.Columns.Count - 1 'columns 
      pos = Chr(Asc("A") + (j)) & i 'calculate the column according to j 
      'after this, pos will have the right excel cell. 
      xlWorkSheet.Range(pos).Value = datatable.Rows(i)(j) 
     Next 
    Next 

這裏的要點是,你可以使用正確的字符串來表示excel範圍...

+0

那是天才!謝謝! – Nonagon

相關問題