I have a little issue regarding writing queried data to an xlsx file but not in consecutive columns
The code below is a snippet regarding my current method of writing the four columns of a query to a spreadsheet starting at C6, so the data is in C, D, E and F.
My interest now is to write the same dataset to columns C, E, H, and L. Can anyone give me a hint?
Thanks in advance
Richard
Dim da As SqlDataAdapter
da = New SqlDataAdapter(Query1, SQLConn)
Dim ds As New DataSet
Dim i, j As Integer
da.Fill(ds)
'Write to Excel
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
xlSht.Cells(i + 6, j + 3) = ds.Tables(0).Rows(i).Item(j).ToString
Next
Next
One option is to create an array of column indexes like this:
Dim colIndexes As Integer() = {2, 4, 7, 11} '{C, E, H, L}
Then replace j+3
with colIndexes(j)
to write into the correct cell
xlSht.Cells(i + 6, colIndexes(j)) = ds.Tables(0).Rows(i).Item(j).ToString