Exporting DataGridView to Excel File

Good day all!
Somebody please help me about this problem that I encounter with exporting from DataGridView to Excel File. I'm still new to VB.Net and all programming stuff so please bear with me if I might sound so stupid and all.. :D
This is the error that I get:
An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe
Additional information: Object reference not set to an instance of an object.
This is the code that I have:
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _ ' the error takes place here as per debugger
DataGridView1(j, i).Value.ToString() ' the error takes place here as per debugger
Next
Next
xlWorkSheet.SaveAs("C:\Book1.xls")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\Book1.xls")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
thanks for all your future help and God bless :)
Geee

thanks for all your help, I just needed to restart my PC and all these codes work. this is my final code:
Module1:
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Module Module1
Public Sub Show1(DataGridView1 As DataGridView)
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each p As Process In pProcess
p.Kill()
Next
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = CType(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
If DataGridView1(j, i).Value IsNot Nothing Then
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
End If
Next
Next
xlWorkSheet.SaveAs(Application.StartupPath & "\" & "GeneratedReport " & Date.Now.ToString("MMdYYYY") & ".xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Module
Calling it:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Show1(DataGridView1)
End Sub
But the column header is not included on the excel file, please help me again, thanks :)
Geee

Similar Messages

  • Any way to export table to excel file with leading 0s?

    I have to export about 50 excel files from different tables.  Some tables contain leading 0s in the columns.  If I use bcp to export to xls file, the leading 0s will be missing.  If bcp to csv or txt file, there will be no issue at all.  But I have to export to xls file in order to let client update that xls file and reload to tables again.
    Is there any other ways to do this task?
    Thanks in advance.

    Ok,  I played with it and fixed it on mine to work.
    Here is what you do.  Create a blank Excel file in Excel with a single header row with your column names in it, and then set the datatypes for each column in Excel to match your export type.  For the below, create an Excel file and in column A1, put "Name" and change the column to Type Text.  Then in B1 type Date and set it to type Date, then save the file as c:\Test.xls.  Then close the file in Excel.
    In SSMS execute the following:
    Code Snippet
    INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=C:\test.xls;HDR=YES',
    'SELECT Name, Date FROM [Sheet1$]')
    SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs
    GO
     It worked perfectly in my environment.  Don't bother with BCP, just create a formated Excel File with a header row with your output column names and then save it.

  • Unable to export report to excel file from SAP

      Hi all,
    I have a problem to download data from a report. The XL gets downloaded in a different format than my colleague.
    We are using the same XL version but two weeks back the SAP GUI 730 got reinstalled to my machine and since then the problem
    started.
    Can you please confirm is there is any particular user settings for this?
    I have login in any different working ( SAP Export ) machine with my login ID and Password and try to export the report to excel file from SAP, and I have same issue . Same we have requested another user to login in my machine with their ID and Password and check the same, They have tried and its working for then in my machine.
    see screenshots attached.
    Thanks.

    Execute report>
    Right click anywhere in the report output and select Spreadsheet.
    A pop up box will appear, select which export option you would like to use and click green check.
    NOTE: If you don't see this option then goto Settings>Switch List then try above said.
    Thanks,
    Kumar

  • Export  data in Excel file - Debug and Break Point

    In the program RFUMSV00 the data  been displayed on the screen with the function REUSE_ALV_LIST_DISPLAY.
    With "Cntrl + Shift + F9" I exported the list of data in an Excel file.
    How can I see, with Debug, where the program RFUMSV00 passed the data to Excel File? I can indicate the point, In the program, where I need to set the break point?
    Thanks,
    Serena

    Hi,
    This download functionality has nothing to have with program RFUMSV00. It is actually processed by REUSE_ALV_LIST_DISPLAY fm, which calls fm LIST_COMMAND which finally calls fm LIST_DOWNLOAD, where you will actually find the downloading part (in fact in another fm, DOWNLOAD_LIST)...
    to resume: REUSE_ALV_LIST_DISPLAY->LIST_COMMAND->LIST_DOWNLOAD->DOWNLOAD_LIST
    so I would put the break-point in the last one..
    Kr,
    Manu.
    correction: I made a mistake, the break-point should be set in LIST_DOWNLOAD...where you will find the call to fm LIST_CONVERT_TO_DAT which is responsible of the download...
    Edited by: Manu D'Haeyer on Dec 9, 2011 1:46 PM

  • Export Report to Excel File & query design??? Urgent

    Hi all,
    1) It seems that I cannot use any BEx tools/function afer I export query report to excel file, such as refresh query report,...etc. If I am wrong, please let me know.
    2) I have about 18 free CHARs in my report as my clien request (all variables are optional), now I only can run the query in the specific period, otherwise the report will show error and cannot run it. Why? is there any way I can fix it?
    Thanks.
    J.

    Hi Prvaeen,
    That is what i see in my excel file after exported.
    Here is the error I got from web report:
    The URL http://sdcbwqa03.amcc.com:8100/sap/bw/BEx was not called due to an error.
    Note
    The following error text was processed in the system BWQ : Invalid dynamic line component.
    The error occurred on the application server sdcbwqa03_BWQ_00 and in the work process 0 .
    The termination type was: RABAX_STATE
    The ABAP call stack was:
    Form: COPY_SETXX_LINE of program CL_RSR_REQUEST================CP
    Form: GET_DATA_CELLS of program CL_RSR_REQUEST================CP
    Form: COMPUTE_NOP of program CL_RSR_LIST_CALCULATION=======CP
    Form: COMPUTE_ORDER of program CL_RSR_LIST_CALCULATION=======CP
    Form: COMPUTE of program CL_RSR_LIST_CALCULATION=======CP
    Form: REQUEST_DATA of program CL_RSR_REQUEST================CP
    Form: READ_DATA_INTERNAL of program CL_RSR_REQUEST================CP
    Form: READ_DATA of program CL_RSR_REQUEST================CP
    Form: READ_DATA of program CL_RSR_WWW_VIEW===============CP
    Form: RENDER of program CL_RSR_WWW_ITEM===============CP
    Thanks.
    J.

  • Numbers 2.1 when exported as an excel file and my application tries opening it, it says file contains corrupt data.

    I recently updated my iPad to the latest iOS 7 and updated my numbers app to 2.1. When i export it to a excel file and then when my C# application(using gembox library) tries reading it, i would get an error "file contains corrupt data". before making the update to iOS 7 and before updating my numbers the process worked fine!

    That didn't work for me and the page times out right about 5
    minutes (300 seconds). I don't have timeout checked in the CF
    Administrator so I don't think it is CF that is causing the
    timeout. I checked IIS also and the timeout is set to 900 seconds.
    Is there a possibility that SQL Server has some sort of
    connection limit and I'm using too many cfquery tags? If anyone has
    experienced a similar problem I would really appreciate the help,
    thanks.

  • Export data to EXCEL file

    Hello All,
    I have 3 internal tables and I need them exported to an one excel file.
    It will have two headers, that shows the description and the other ones will show the DATA.
    Here are an example:
    Header Data                                                   Stage Data                Delivery Data               
    Shipment     Service Agent     Name      SCAC       Stage     Origin     Name     Origin       Region
    12124     51054     LTL Carrier     RLQD     u2026     1     Philadelphia           PA     u2026
    12124     51054     LTL Carrier     RLQD     u2026     2     New York          NY     u2026
    12124     51054     LTL Carrier     RLQD     u2026     2     New York          NY     u2026
    Do you know what kind of function module should I use?
    Thank you,
    Ricardo

    Hi,
    Check out this LINK
    ps: Don´t forget to scroll down..the rest of the code is at the end of the page

  • Exporting data to Excel file

    I am curious what the "best practice" is for exporting data programmaticly from SQL Server to Excel.  Is it best to do it straight from SQL Server, or should I do it with in my C# code?  My program is going to pull the data, put in the
    excel file, then email the file.  So I could write an SP that gets the data and puts it in the file, then have the C# code run the SP and email the file; Or I could have the code do everything, pull the data, export it & email it.
    If it is considered better to have the SP do it, why and what is the best way? ROWSET functions?

    So I could write an SP that gets the data and puts it in the file, then have the C# code run the SP and email the file; Or I could have the code do everything, pull the data, export it & email it.
    A very important thing to consider is where the Excel file should reside who should do the mailing, the client or the server?
    I would definitely recommend having a C# program to get the data and write to the Excel book. Writing to Excel books from SQL Server is possible, but there is a lot more problems with permissions, OLE DB providers etc. Plus, neither writing to Excel books
    nor sending mail is part of the core business for SQL Server which is to work with data.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Export as a excel file

    yes I know its a common question. But I jsut need some feedback on.
    1) Can a SAVE AS window be opened like when you save a image on IE?
    2) Wich is the best way to apply the export? using Java Excel API or another?
    3) Since its my first time is there some tuts, example or even a demo I can use as a guide ?
    Thanks a lot !

    1) Yes, although this is browser dependent. When you send the execl file to the browser you need to set the content type appropriately. If your browser doesn't know how to handle a spreadsheet it will prompt the user to save / find a program to open. Unfortunately if your browser knows how to handle excel files it just opens it as an embeded object.
    I believe that you may be able to prevent this by setting the content type appropriately, but I can't remember the exact syntax.
    2) It depends on how complicated your spreadsheet is. If you only need one worksheet, no formatting or formulas etc then you could export as a CSV file. There are issues with this approach though. If the data contains commas you need delimit fields using quotation marks and prefix naturally occuring quotation marks with apostrophes (think this is right). e.g.
    field1,field2,fie,ld3,fie"ld4
    must become
    field1,field2,"fie,ld3",fie'"ld4
    Also 1/10 must become ="1/10" unless you want excel to display 1-Jan
    Finally this is based on Microsoft CVS format, however CSV is not a standard. Other CSV readers assume that naturally occuring " or , characters will be preceded by a \ character.
    The alternative is to use a library to generate excel files. Check out http://jakarta.apache.org/poi/index.html. I've never used it though.

  • Error exporting data to excel file

    Hello,
    I have written a macro to export some channels into an excel file, skipping the excel wizard by using the following code:
    EXCELChnCount = intChannels - 1
    For i = 1 To intChannels
        ExcelExpChn(i) = ChannelList(i - 1)
    Next
    Call EXCELExport ("c:\test.xls","data",0,"")
    No file is created, but when I output EXCELStat / EXCELStatTex it contains the error code 100 "a general error occured".
    The strange thing is, if I run the wizard once (by changing the 0 to a 1), and just press "finish", the wizard-less export works flawlessly afterwards.
    Has anybody an idea what is wrong? Do I have so set some more variables in order to make it work without using the wizard?
    Using a STP configuration file, as I've read in some other postings isn't an option, as the name and the numbers of the exported channels change constantly.
    Thanks for your help, and best regards!
    Sam

    Hi Sam,
    I did not try your script out, but I often receive the mysterious "error 100" when Excel already has the file open - Excel is very protective of its open files.  Sometimes Excel will crash too, but checking your Task Manager will reveal it is still running...
    Julia

  • Oracle query export into the Excel file

    Hi,
    How can i automatically export oracle query result into the excel file in oracle?

    SQL and PL/SQL FAQ
    Re: Excel query to Oracle Database
    http://blog.mclaughlinsoftware.com/microsoft-excel/how-to-query-oracle-from-excel-2007/
    Edited by: swapnil kambli on May 28, 2013 11:07 PM

  • Acrobat X Pro exporting to blank excel file

    the excel file is empty except for the title of the document.  no data whatsoever

    Was the file a bunch of bitmaps or actual text?

  • Exporting Discoverer to Excel file - using command line ....

    Hi Everyone,
    The discoverer report has the parameter in the title.
    When I click on the Xcel button in Disco., the title with parm gets included in spreadsheet
    -but-
    I really want to run the command line to send Disco. output to Excel.
    The title line is not there!!!! (but column headings with data are there)
    I really need the parm value to be included in the Excel header. Any ideas, pls? tx, Sandra
    command line:
    C:\oracle\BIToolsHome_1\bin\dis51usr.exe /connect testuser/tstuser123@odstest /opendb "testuser.ToWeb_Elective_Tally.DIS" /sheet ALL /parameter parm_AcademicPeriod "200910, 200920" /export XLS "C:\ARG_99_Scripts\ARG_99_DailyElectives_script\ToWeb_Elective_Tally.xls" /batch

    Hi,
    You could try using /export HTML but keep the file type as .xls. Then you will open the HTML file in excel and most of the formatting and title will be preserved.
    However, you will not be able to use /sheet ALL with the /export HTML option.
    Rod West

  • How to export the text edit data to excel file without splitting the data in excel file?

    how to export the text edit data to excel file without splitting the data in excel file?
    I have a requirement in SAP HR where in the appraiser can add comments in the area given and can export that to excel file. Currently the file is getting exported but the comments getting split into deifferent rows.
    I want the entire comment to be fit in one row.
    Please help.
    Thank you

    Hi,
    if your text edit value is stored in 'lv_string' variable.
    then before exporting the value to excel you have to remove CL_ABAP_CHAR_UTILITIES=>NEWLINE
    that is '#' from the variable lv_string.
    for that use code some thing like this.
    REPLACE ALL OCCURRENCES OF CL_ABAP_CHAR_UTILITIES=>NEWLINE in lv_string WITH space.
    I think this will do the trick.

  • WEBI report present different in exported excel file

    Hello expert,
         I create a line chart in webi, and I create a table block to cover the x axies label for the line chart.  this presentation looks perfect in WEBI report, but when I export it into excel file, the x axies labels for the line chart showed up with that table block moved down a little bit.  how can I present WEBI in the same way in the exported excel file?

    Hi,
    If your requirement is to hide labels or  X Axis values from the chart ..You can do this directly unchecked the check box for values or labels from the  X Axis properties.
    For to adjust the table block and line chart  right click on the  Cell go to Align ->Relative Position and in the bottom section adjust the  height  from  the particular block.
    Hope this helps you.
    Thanks,
    Amit

Maybe you are looking for

  • JCO version installed in CE 7.1 sp11

    Hi, I need to check the JCO version installed in CE 7.1 sp 11. Please let me know how to check the same? Regards Radhika Kuthiala

  • X4100 LOM problems out of the box

    Straight out of the box I am having trouble connecting to lom. Using a serial cable I can connect and see the lom service start after power is connected, when the login line appears i loose control of the session. Any ideas? I don't know what the IP

  • Find my phone no longer allows us to send a message??

    Did they remove this option?

  • So i have mpg and avi vids, now what lol?

    Hey guys well i just got my ipod video and wel it freagin awesome lol. But i have bunch of MPG. adn AVI. videos and i used this program i use to convert vids for my psp and i have the vids in MP4. format now. But the thing is i dont no what to do nex

  • I cannot access music in lock screen

    After updating to ios 7, using the control panel I cannot play music from my lock screen. I can press play and skip all I want and it will not do anything. I have to unlock my phone and go into music to play the music. Once locked, the small music pl