在excel工作表中为父表中的每一行打印子表数据
Posted
技术标签:
【中文标题】在excel工作表中为父表中的每一行打印子表数据【英文标题】:printing child table data for each row in the parent table in excel sheet 【发布时间】:2014-12-15 10:11:47 【问题描述】:我有两个数据集,其中一个表中有品牌,另一个表中有产品。我必须将此信息导出到 excel 中,例如打印 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()
原来是这样的
【问题讨论】:
【参考方案1】:这种给你类似的布局
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()
【讨论】:
以上是关于在excel工作表中为父表中的每一行打印子表数据的主要内容,如果未能解决你的问题,请参考以下文章