我只想先提一下,我非常感谢所有提供知识帮助他人学习的人......
我已经能够拼凑将我的 Datgrid 导出到 Excel 文件的代码并且工作正常,除了我只得到数据网格的第一行。由于数据网格可能包含一条或数百条记录,因此我需要将所有行导出到 Excel。
这是我能够放在一起的内容(再次,它工作正常,文件与列标题一起保存,但只从我的数据网格写入第一行数据):
'Export to Excel
Dim ExApp1 As Excel.Application
Dim ExWkbk1 As Excel.Workbook
Dim ExWksht1 As Excel.Worksheet
Dim MisValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
ExApp1 = New Excel.Application
ExWkbk1 = ExApp1.Workbooks.Add(MisValue)
ExWksht1 = ExWkbk1.Sheets("sheet1")
For i = 0 To dg7.RowCount - 2
For j = 0 To dg7.ColumnCount - 1
ExWksht1.Cells(i + 2, j + 1) = dg7(j, i).Value.ToString()
For k As Integer = 1 To dg7.Columns.Count
ExWksht1.Cells(1, k) = dg7.Columns(k - 1).HeaderText
ExWksht1.Cells(i + 2, j + 1) = dg7(j, i).Value.ToString()
Next
Next
Next
ExWksht1.SaveAs("C:\MyExcel.xlsx")
ExWkbk1.Close()
ExApp1.Quit()
releaseObject(ExApp1)
releaseObject(ExWkbk1)
releaseObject(ExWksht1)
再次感谢您帮助我学习