使用VB.NET将特定的数据库数据添加到excel文件

我想添加数据到一个Excel文件中,我build立了一个连接数据库,并使用SSMS将需要的信息提取到存储过程中。

我已经添加了基于我需要的信息的列,一些行将是静态数据这里是我的代码:

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文件并包含信息。

我是新来的,所以会欣赏一些指导

我们以此为例

比方说,我已经把第二个查询拉入数据表。 我将按照该顺序将其填充到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 

这里的要点是,你可以使用正确的string来表示excel范围。