VB.NET - Create Excel Spreadsheet From Array-VBForums
Results 1 to 12 of 12

Thread: VB.NET - Create Excel Spreadsheet From Array

  1. #1

    Thread Starter
    Hyperactive Member ProphetBeal's Avatar
    Join Date
    Aug 2006
    Location
    New York
    Posts
    424

    VB.NET - Create Excel Spreadsheet From Array


    This is a short method that accepts a 2 dimensional string array and turns it into an excel spreadsheet. You can also pass a file name and it will save the spreadsheet. FYI...As noted in the code I'm using late binding to avoid version issues with Excel.

    This is the Original code. See Below (post 4) for the Updated Code
    VB Code:
    1. Public Sub WriteSpreadsheetFromArray(ByRef strOutputArray(,) As String, Optional ByVal strExcelFileOutPath As String = "")
    2.         'To avoid conflicts with different versions of Excel...We are using late binding.
    3.         Dim objxlOutApp As Object 'Excel.Application
    4.         Dim objxlOutWBook As Object 'Excel.Workbook
    5.         Dim objxlOutSheet As Object 'Excel.Worksheet
    6.         Dim objxlRange As Object 'Excel.Range
    7.  
    8.         Try
    9.             'Try to Open Excel, Add a workbook and worksheet
    10.             objxlOutApp = CreateObject("Excel.Application") 'New Excel.Application
    11.             objxlOutWBook = objxlOutApp.Workbooks.Add '.Add.Sheets
    12.             objxlOutSheet = objxlOutWBook.Sheets.Item(1)
    13.         Catch ex As Exception
    14.             MessageBox.Show("While trying to Open Excel recieved error:" & ex.Message, "Export to Excel Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    15.             Try
    16.                 If Not IsNothing(objxlOutWBook) Then
    17.                     objxlOutWBook.Close()  'If an error occured we want to close the workbook
    18.                 End If
    19.                 If Not IsNothing(objxlOutApp) Then
    20.                     objxlOutApp.Quit() 'If an error occured we want to close Excel
    21.                 End If
    22.             Catch
    23.             End Try
    24.             objxlOutSheet = Nothing
    25.             objxlOutWBook = Nothing
    26.             If Not IsNothing(objxlOutApp) Then
    27.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(objxlOutApp)  'This will release the object reference
    28.             End If
    29.             objxlOutApp = Nothing
    30.             Exit Sub 'An error occured so we don't want to continue
    31.         End Try
    32.  
    33.         Try
    34.             objxlOutApp.DisplayAlerts = False    'This will prevent any message prompts from Excel (IE.."Do you want to save before closing?")
    35.             objxlOutApp.Visible = False    'We don't want the app visible while we are populating it.
    36.  
    37.             'This is the easiest way I have found to populate a spreadsheet
    38.             'First we get the range based on the size of our array
    39.             objxlRange = objxlOutSheet.Range(Chr(strOutputArray.GetLowerBound(1) + 1 + 64) & (strOutputArray.GetLowerBound(0) + 1) & ":" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64) & (strOutputArray.GetUpperBound(0) + 1))
    40.             'Next we set the value of that range to our array
    41.             objxlRange.Value = strOutputArray
    42.             'This final part is optional, but we Auto Fit the columns of the spreadsheet.
    43.             objxlRange.Columns.AutoFit()
    44.  
    45.             If strExcelFileOutPath.Length > 0 Then 'If a file name is passed
    46.                 Dim objFileInfo As New IO.FileInfo(strExcelFileOutPath)
    47.  
    48.                 If Not objFileInfo.Directory.Exists Then 'Check if folder exists
    49.                     objFileInfo.Directory.Create() 'If not we create it
    50.                 End If
    51.                 objFileInfo = Nothing
    52.  
    53.                 objxlOutWBook.SaveAs(strExcelFileOutPath)  'Then we save our file.
    54.             End If
    55.             objxlOutApp.Visible = True 'Make excel visible
    56.         Catch ex As Exception
    57.             MessageBox.Show("While trying to Export to Excel recieved error:" & ex.Message, "Export to Excel Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    58.             Try
    59.                 objxlOutWBook.Close()  'If an error occured we want to close the workbook
    60.                 objxlOutApp.Quit() 'If an error occured we want to close Excel
    61.             Catch
    62.             End Try
    63.         Finally
    64.             objxlOutSheet = Nothing
    65.             objxlOutWBook = Nothing
    66.             If Not IsNothing(objxlOutApp) Then
    67.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(objxlOutApp) 'This will release the object reference
    68.             End If
    69.             objxlOutApp = Nothing
    70.         End Try
    71.     End Sub
    Last edited by ProphetBeal; Mar 2nd, 2007 at 01:09 PM. Reason: Added note for new code

    Helpful Links:
    VB 6 - How to get the "Key" Value in a collection
    VB.NET - File Search Utility || VB.NET - How to compare 2 directories || VB.NET - How to trust a network share
    VB.NET - Create Excel Spreadsheet From Array || VB.NET - Example Code & Hints you may not know
    VB.NET - Save JPEG with a certain quality (image compression) || VB.NET - DragDrop Files, Emails, and Email Attachments

    Please post some of the code you need help with (it makes it easier to help you)
    If your problem has been solved then please mark the thread [RESOLVED].
    Don't forget to Rate this post

    "Pinky, you give a whole new meaning to the phrase, 'counter-intelligence'."-The Brain-

  2. #2
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,176

    Re: VB.NET - Create Excel Spreadsheet From Array

    you might want to mention that the code requires the use of the Office Interop Assemblies
    Currently using: VS 2015 Enterprise on Win7 Ultimate x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  3. #3
    Super Moderator RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,276

    Re: VB.NET - Create Excel Spreadsheet From Array

    Also, the use of ReleaseComObject should not be needed ever if the object variables are handled correctly.

    Lastly, you shouold have Option Strict On which will generate several errors as the code doesnt have any casting.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Star Wars Gangsta Rap Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel Core 2 Extreme Ed., 2 Intel 300 GB SSDs, 2 GBs DDR2 667 MHz RAM, 2 Viewsonic 24" LCDs, Windows 7 SP-1, Office 2010, VS 2013

  4. #4

    Thread Starter
    Hyperactive Member ProphetBeal's Avatar
    Join Date
    Aug 2006
    Location
    New York
    Posts
    424

    Re: VB.NET - Create Excel Spreadsheet From Array

    Thanks for the feedback guys. I have updated the code with Option Strict On. In order to use this code you will need to add a reference to the Microsoft Excel Object Library.
    VB Code:
    1. Public Sub WriteSpreadsheetFromArray(ByRef strOutputArray(,) As String, Optional ByVal strExcelFileOutPath As String = "")
    2.         Dim objxlOutApp As Excel.Application
    3.         Dim objxlOutWBook As Excel.Workbook
    4.         Dim objxlOutSheet As Excel.Worksheet
    5.         Dim objxlRange As Excel.Range
    6.  
    7.         Try
    8.             'Try to Open Excel, Add a workbook and worksheet
    9.             objxlOutApp = New Excel.Application
    10.             objxlOutWBook = objxlOutApp.Workbooks.Add '.Add.Sheets
    11.             objxlOutSheet = DirectCast(objxlOutWBook.Sheets.Item(1), Excel.Worksheet)
    12.         Catch ex As Exception
    13.             MessageBox.Show("While trying to Open Excel recieved error:" & ex.Message, "Export to Excel Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    14.             Try
    15.                 If Not IsNothing(objxlOutWBook) Then
    16.                     objxlOutWBook.Close()  'If an error occured we want to close the workbook
    17.                 End If
    18.                 If Not IsNothing(objxlOutApp) Then
    19.                     objxlOutApp.Quit() 'If an error occured we want to close Excel
    20.                 End If
    21.             Catch
    22.             End Try
    23.             objxlOutSheet = Nothing
    24.             objxlOutWBook = Nothing
    25.             'If Not IsNothing(objxlOutApp) Then
    26.             'System.Runtime.InteropServices.Marshal.ReleaseComObject(objxlOutApp)  'This will release the object reference
    27.             'End If
    28.             objxlOutApp = Nothing
    29.             Exit Sub 'An error occured so we don't want to continue
    30.         End Try
    31.  
    32.         Try
    33.             objxlOutApp.DisplayAlerts = False    'This will prevent any message prompts from Excel (IE.."Do you want to save before closing?")
    34.             objxlOutApp.Visible = False    'We don't want the app visible while we are populating it.
    35.  
    36.             'This is the easiest way I have found to populate a spreadsheet
    37.             'First we get the range based on the size of our array
    38.             objxlRange = objxlOutSheet.Range(Chr(strOutputArray.GetLowerBound(1) + 1 + 64) & (strOutputArray.GetLowerBound(0) + 1) & ":" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64) & (strOutputArray.GetUpperBound(0) + 1))
    39.             'Next we set the value of that range to our array
    40.             objxlRange.Value = strOutputArray
    41.             'This final part is optional, but we Auto Fit the columns of the spreadsheet.
    42.             objxlRange.Columns.AutoFit()
    43.  
    44.             If strExcelFileOutPath.Length > 0 Then 'If a file name is passed
    45.                 Dim objFileInfo As New IO.FileInfo(strExcelFileOutPath)
    46.  
    47.                 If Not objFileInfo.Directory.Exists Then 'Check if folder exists
    48.                     objFileInfo.Directory.Create() 'If not we create it
    49.                 End If
    50.                 objFileInfo = Nothing
    51.  
    52.                 objxlOutWBook.SaveAs(strExcelFileOutPath)  'Then we save our file.
    53.             End If
    54.             objxlOutApp.Visible = True 'Make excel visible
    55.         Catch ex As Exception
    56.             MessageBox.Show("While trying to Export to Excel recieved error:" & ex.Message, "Export to Excel Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    57.             Try
    58.                 objxlOutWBook.Close()  'If an error occured we want to close the workbook
    59.                 objxlOutApp.Quit() 'If an error occured we want to close Excel
    60.             Catch
    61.             End Try
    62.         Finally
    63.             objxlOutSheet = Nothing
    64.             objxlOutWBook = Nothing
    65.             'If Not IsNothing(objxlOutApp) Then
    66.             '    System.Runtime.InteropServices.Marshal.ReleaseComObject(objxlOutApp) 'This will release the object reference
    67.             'End If
    68.             objxlOutApp = Nothing
    69.         End Try
    70.     End Sub

    Helpful Links:
    VB 6 - How to get the "Key" Value in a collection
    VB.NET - File Search Utility || VB.NET - How to compare 2 directories || VB.NET - How to trust a network share
    VB.NET - Create Excel Spreadsheet From Array || VB.NET - Example Code & Hints you may not know
    VB.NET - Save JPEG with a certain quality (image compression) || VB.NET - DragDrop Files, Emails, and Email Attachments

    Please post some of the code you need help with (it makes it easier to help you)
    If your problem has been solved then please mark the thread [RESOLVED].
    Don't forget to Rate this post

    "Pinky, you give a whole new meaning to the phrase, 'counter-intelligence'."-The Brain-

  5. #5
    Super Moderator RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,276

    Re: VB.NET - Create Excel Spreadsheet From Array

    Yes, with Option Strict On you will have to either add thereference and switch to Early Binding or use Reflection and have it as Late Binding with Option Strict On. Its allot of work to use Late Binding with Reflection so unless there is a good reason for late binding I would just early bind.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Star Wars Gangsta Rap Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel Core 2 Extreme Ed., 2 Intel 300 GB SSDs, 2 GBs DDR2 667 MHz RAM, 2 Viewsonic 24" LCDs, Windows 7 SP-1, Office 2010, VS 2013

  6. #6
    New Member
    Join Date
    Apr 2008
    Posts
    1

    Re: VB.NET - Create Excel Spreadsheet From Array

    thanks for the post - it acutally works - would change the last part since the spreadsheet stays locked by the system and you can't delete it - i am creating this in a web app to download - will probably bring the ire of those who will say this automation was not meant to be used on a server. sorry bout that.

    revised code is
    Public Sub WriteSpreadsheetFromArray(ByRef strOutputArray(,) As String, Optional ByVal strExcelFileOutPath As String = "")
    Dim objxlOutApp As Microsoft.Office.Interop.Excel.Application

    .
    .
    .
    If strExcelFileOutPath.Length > 0 Then
    'If a file name is passed
    Dim objFileInfo As New IO.FileInfo(strExcelFileOutPath)
    If Not objFileInfo.Directory.Exists Then 'Check if folder exists
    objFileInfo.Directory.Create() 'If not we create it
    End If
    objFileInfo = Nothing
    objxlOutWBook.SaveAs(strExcelFileOutPath) 'Then we save our file.

    End If


    Catch ex As Exception


    End Try

    Try
    objxlOutWBook.Close() 'want to close the workbook
    objxlOutApp.Quit() 'want to close Excel


    Finally
    objxlOutSheet = Nothing
    objxlOutWBook = Nothing
    objxlOutApp = Nothing
    End Try

    End Sub

  7. #7
    New Member
    Join Date
    Jun 2008
    Posts
    1

    Post Re: VB.NET - Create Excel Spreadsheet From Array

    This works well up to 26 columns in Excel 2003. However, it breaks when computing the upper bound going from Z to AA.

    If you replace line 38 with the following code in the version posted by ProphetBeal on Mar 2nd, 2007, 01:03 PM, all columns up to IV are accepted.

    'Let's determine the column name
    Dim sUpperBoundLetter As String
    Select Case strOutputArray.GetUpperBound(1)
    Case Is > 234
    sUpperBoundLetter = "I" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26 - 26 - 26 - 26 - 26 - 26)
    Case Is > 208
    sUpperBoundLetter = "H" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26 - 26 - 26 - 26 - 26)
    Case Is > 182
    sUpperBoundLetter = "G" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26 - 26 - 26 - 26)
    Case Is > 156
    sUpperBoundLetter = "F" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26 - 26 - 26)
    Case Is > 130
    sUpperBoundLetter = "E" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26 - 26)
    Case Is > 104
    sUpperBoundLetter = "D" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26 - 26)
    Case Is > 78
    sUpperBoundLetter = "C" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26 - 26)
    Case Is > 52
    sUpperBoundLetter = "B" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26 - 26)
    Case Is > 26
    sUpperBoundLetter = "A" & Chr(strOutputArray.GetUpperBound(1) + 1 + 64 - 26)
    Case Else
    sUpperBoundLetter = Chr(strOutputArray.GetUpperBound(1) + 1 + 64)
    End Select

    objxlRange = objxlOutSheet.Range(Chr(strOutputArray.GetLowerBound(1) + 1 + 64) & (strOutputArray.GetLowerBound(0) + 1) & ":" & sUpperBoundLetter & (strOutputArray.GetUpperBound(0) + 1))

  8. #8
    Hyperactive Member
    Join Date
    Mar 2008
    Posts
    470

    Re: VB.NET - Create Excel Spreadsheet From Array

    How to call this method if I pass one dimension string array?

  9. #9

    Thread Starter
    Hyperactive Member ProphetBeal's Avatar
    Join Date
    Aug 2006
    Location
    New York
    Posts
    424

    Re: VB.NET - Create Excel Spreadsheet From Array

    Quote Originally Posted by zhshqzyc
    How to call this method if I pass one dimension string array?
    Well this was created to handle 2 dimensional arrays. 1 dimension for the rows and a 2nd for the columns. If you only have a 1 dimension array where would the data be populated? A single row or a single column?

    Helpful Links:
    VB 6 - How to get the "Key" Value in a collection
    VB.NET - File Search Utility || VB.NET - How to compare 2 directories || VB.NET - How to trust a network share
    VB.NET - Create Excel Spreadsheet From Array || VB.NET - Example Code & Hints you may not know
    VB.NET - Save JPEG with a certain quality (image compression) || VB.NET - DragDrop Files, Emails, and Email Attachments

    Please post some of the code you need help with (it makes it easier to help you)
    If your problem has been solved then please mark the thread [RESOLVED].
    Don't forget to Rate this post

    "Pinky, you give a whole new meaning to the phrase, 'counter-intelligence'."-The Brain-

  10. #10
    Hyperactive Member
    Join Date
    Mar 2008
    Posts
    470

    Re: VB.NET - Create Excel Spreadsheet From Array

    Thanks.
    I resloved it.


    But I deploy the executable to my flash drive(run .exe file), I get an "Unhandled exception error" stating "Could not find file or assembly "Interop.Excel."

    Do I need to add more ferences or modify the codes?
    Or shall I copy something to the flash drive?

    I am using your the earliest code.
    Last edited by zhshqzyc; Feb 5th, 2009 at 05:23 PM.

  11. #11
    Hyperactive Member
    Join Date
    Mar 2008
    Posts
    470

    Re: VB.NET - Create Excel Spreadsheet From Array

    The code is good except one thing.
    If there is an excel file opened. It can't been export it to the excel file.
    Any advice?

  12. #12
    Fanatic Member stlaural's Avatar
    Join Date
    Sep 2007
    Location
    Quebec, Canada
    Posts
    683

    Re: VB.NET - Create Excel Spreadsheet From Array

    Nice Thread, helped a lot, thanks.
    Alex
    .NET developer
    "No. Not even in the face of Armageddon. Never compromise." (Walter Kovacs/Rorschach)

    Things to consider before posting.
    Don't forget to rate the posts if they helped and mark thread as resolved when they are.


    .Net Regex Syntax (Scripting) | .Net Regex Language Element | .Net Regex Class | DateTime format | Framework 4.0: what's new
    My fresh new blog : writingthecode, even if I don't post much.

    System: Intel i7 920, Kingston SSDNow V100 64gig, HDD WD Caviar Black 1TB, External WD "My Book" 500GB, XFX Radeon 4890 XT 1GB, 12 GBs Tri-Channel RAM, 1x27" and 1x23" LCDs, Windows 10 x64, ]VS2015, Framework 3.5 and 4.0

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.