Question

I'm trying to automate the filling of a master excel file from selected rows in a datagridview element. I've already hooked up the database to the datagrid and I am attempting to populate certain fields in the excel spreadsheet, based on selected row(s) of the data grid.

    Dim objExcel As New Excel.Application
    objExcel.Workbooks.Add("path of master workbook")
    '
    objExcel.Visible = True

    'Select and modify cells 

    'Site(Name)

    objExcel.Range("B2").Select()
    objExcel.ActiveCell.FormulaR1C1() = 'Where I want to specify the value

From the research I've done, I'll need to use the selectionchanged event of my datagrid to identify the selected rows, then populate the spreadsheet based on the column index, then use a loop for the remaining fields to populate. I'd also like to add the ability to create multiple sheets, by looping through the selected rows in the datagrid view.

I've looked at many different code samples for exporting the entire datagrid to Excel, but I can't for the life of me figure out how to obtain the value of only the selected row, and then further the individual cell values based on column.

Can someone point me in the right direction, or just let me know that I'm completely off base?

Was it helpful?

Solution

To set the value of a cell you can just use

objExcel.Range("B2").Value = "whatever"

There's no need to select a cell to set its value. Since you're going to be looping through rows/columns and inserting values, you may find it's more convenient to use a different approach to addressing specific cells:

objExcel.Cells(2,2).Value = "whatever"  'row,column

I'm not sure you need to capture events on your datagridview (unless you're automatically writing rows as they're being selected): i'm guessing you have a button or something to trigger the export, so all you need to dso is look at the dgv's SelectedRows

http://msdn.microsoft.com/en-us/library/x8x9zk5a.aspx#Y0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top