프로그래밍언어/VB.NET

array to excel

부산딸랑이 2019. 3. 1. 11:43

Imports Excel = Microsoft.Office.Interop.Excel


Public Class Form1

    'Keep the application object and the workbook object global, so you can  

    'retrieve the data in Button2_Click that was set in Button1_Click.

    Dim objApp As Excel.Application

    Dim objBook As Excel._Workbook



    Private Sub Button1_Click(ByVal sender As System.Object, _

      ByVal e As System.EventArgs) Handles Button1.Click

        Dim objBooks As Excel.Workbooks

        Dim objSheets As Excel.Sheets

        Dim objSheet As Excel._Worksheet

        Dim range As Excel.Range


        ' Create a new instance of Excel and start a new workbook.

        objApp = New Excel.Application()

        objBooks = objApp.Workbooks

        objBook = objBooks.Add

        objSheets = objBook.Worksheets

        objSheet = objSheets(1)


        'Get the range where the starting cell has the address

        'm_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.

        range = objSheet.Range("A1", Reflection.Missing.Value)

        range = range.Resize(500, 500)


        If (Me.FillWithStrings.Checked = False) Then

            'Create an array.

            Dim saRet(5, 5) As Double


            'Fill the array.

            Dim iRow As Long

            Dim iCol As Long

            For iRow = 0 To 5

                For iCol = 0 To 5


                    'Put a counter in the cell.

                    saRet(iRow, iCol) = iRow * iCol

                Next iCol

            Next iRow


            'Set the range value to the array.

            range.Value = saRet


        Else

            'Create an array.

            Dim saRet(5, 5) As String


            'Fill the array.

            Dim iRow As Long

            Dim iCol As Long

            For iRow = 0 To 5

                For iCol = 0 To 5


                    'Put the row and column address in the cell.

                    saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()

                Next iCol

            Next iRow


            'Set the range value to the array.

            range.Value = saRet

        End If


        'Return control of Excel to the user.

        objApp.Visible = True

        objApp.UserControl = True


        'Clean up a little.

        range = Nothing

        objSheet = Nothing

        objSheets = Nothing

        objBooks = Nothing

    End Sub