打印excel表中父表中每行的子表数据

时间:2014-12-15 10:11:47

标签: sql vb.net excel

我有两个数据集,其中我在一个表中有品牌,在其他表中有产品。我必须将此信息导出为ex​​cel,例如打印excel中的第一行,然后打印该行下面的所有相关产品等等

Brandname      BrandID
Nike              1

Nike Shoes        1               240$
Nike Shirts      23                78$

yamaha            1

Bike              13               2440$
motor             233              4578$

我已经这样做了,但它没有正确地对齐

Dim i, j As Integer

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

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



        For i = 0 To ds.Tables(0).Rows.Count - 1
            For j = 0 To ds.Tables(0).Columns.Count - 1
                xlWorkSheet.Cells(i + 1, j + 1) = _
                ds.Tables(0).Rows(i).Item(j)

            Next
            For k = 0 To ds2.Tables(0).Rows.Count - 1
                For l = 0 To ds2.Tables(0).Columns.Count - 1
                    xlWorkSheet.Cells(i + k + 2, i + l + 2) = _
                    ds2.Tables(0).Rows(k).Item(l)

                Next
            Next
        Next

        xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
        xlWorkBook.Close()
        xlApp.Quit()

它出现了这样的

enter image description here

1 个答案:

答案 0 :(得分:0)

这种类型给你类似的布局

Dim i, j As Integer

Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
Dim innerCount = 0

For i = 0 To table1.Rows.Count - 1
    For j = 0 To table1.Columns.Count - 1
        xlWorkSheet.Cells(i + innerCount + 2, j + 1) = table2.Rows(i).Item(j)

    Next
    Dim productsForBrand = innertabledata.[Select]("brandID=" & table1.Rows(i).Item("ID")).CopyToDataTable()
    If productsForBrand .Rows.Count > 0 Then
        For k = 0 To productsForBrand .Rows.Count - 1
            For l = 0 To productsForBrand .Columns.Count - 1
                xlWorkSheet.Cells(i + k + innerCount + 3, l + 1) = productsForBrand .Rows(k).Item(l)
            Next
        Next

    End If

    innerCount = innerCount + productsForBrand .Rows.Count
Next

xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()