Dim sd As New SaveFileDialog'声明保存文件对话框 如果sd.ShowDialog = System.Windows.Forms.DialogResult.OK然后'选中路径后检查保存文件对话框是否关闭 'MsgBox(sd.FileName) xlWorkSheet.SaveAs(sd.FileName& .xlsx)'sd.filename重新保存文件对话框路径 xlWorkBook.Close() xlApp.Quit() 结束If releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) MsgBox(你可以找到文件& sd.FileName&。xlsx)Im new to this vb codes my problem is i want to export selected rows in datagridview to excel anyone who can help me ? what codes i can use? thank you in advance!What I have tried:im trying this codes but it gives me all rows in datagridview but i need is the selected row Dim xlApp As Microsoft.Office.Interop.Excel.Application Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Integer Dim j As Integer xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To DataGridView1.RowCount - 2 DataGridView1.Rows(i).Height = 20 For j = 0 To DataGridView1.ColumnCount - 1 For k As Integer = 1 To DataGridView1.Columns.Count xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText xlWorkSheet.Cells.RowHeight = 20 xlWorkSheet.Cells.ColumnWidth = 20 xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString() Next Next Next Dim sd As New SaveFileDialog 'declare save file dialog If sd.ShowDialog = System.Windows.Forms.DialogResult.OK Then 'check if save file dialog was close after selecting a path 'MsgBox(sd.FileName) xlWorkSheet.SaveAs(sd.FileName & ".xlsx") 'sd.filename reurns save file dialog path xlWorkBook.Close() xlApp.Quit() End If releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) MsgBox("You can find the file" & sd.FileName & ".xlsx")推荐答案 代码需要类似 The code need something likeDim selectedRowCount As Integer = _ DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected) If selectedRowCount > 0 Then Dim i As Integer For i = 0 To selectedRowCount - 1 .... .... xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, dataGridView1.SelectedRows(i).Index).Value.ToString() next i End If [如何:获取Windows窗体DataGridView控件中的选定单元格,行和列] 这篇关于如何将datagridview中的选定行导出为ex​​cel VB 2010的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-03 13:37