export data

aletheia

Member
Joined
Jun 27, 2003
Messages
15
How can I export data from a Datagrid to an Excel file?

I know how to do in ASP.NET, but I want to do the same operation in a WindowsForm application.

Thanks in advance
 
here ya go :
Code:
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Dim xlObj As New Excel.Application()
        Dim xlBook As Excel.Workbook
        xlBook = xlObj.Workbooks.Open("C:\Book1.xls")
        xlBook.Sheets("Sheet1").Cells(1, 1).Value = DataGrid1.Item(DataGrid1.CurrentRowIndex, 1)///write the datagrid item to the excel sheet.
        xlBook.Save() ///save the changes to the excel sheet item.
        xlBook.Close()
        xlObj.Quit()
    End Sub
hope that helps :)
 
THANK YOU VERY MUCH!!! But...
It gives me error on "Excel.Application" and "Excel.Workbook" types.

Which namespace should I import?
 
HELP...

I add the reference Excel 9.0 library object, and the errors disappear.

But after clicking the button:

1) the file .xls is locked and I just can open it as "read only"
2) anyway the file is EMPTY...

If I try to close everything, it remains "read only" and empty.

But it doesnt give me any errors... whats wrong with it?
 
if the file is locked and you get a read only message , maybe its already running in the background, try looking in the taskmanager at "processes" , i found i had about 7 instances of excel running once and they shouldnt have been , that was causing a read-only message.
 
Youre right, many Excel processes are running... thats why.

But, thats mean that xlObj.Quit() doesnt work? Because it doesnt close the application...
 
I have Windows NT with service pack 6.
On Windows 2000 the method .Quit() works.

Do you have Windows 2000?
Is it possible that it doesnt work because of the operating system?

Thanx
 
im on Xp , it should work fine , the only thing i can suggest if you are using the Quit and Close , is setting the excel.App and Excel.Workbook to Nothing.
if theres any corruption in the code , it might cause excel to hang in the memory , this has happened to me before.
 
Back
Top