将文本框内容附加到Excel工作表

时间:2017-03-05 11:13:09

标签: excel vb.net vsto

我有以下代码,但我希望每次输入信息而不是覆盖同一个单元格时,我的数据都会添加到excel文件中。 (找到下一个空单元格并向其添加textbox1.text数据)

Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim xlApp As New Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet

    Try
        xlApp.DisplayAlerts = False
        xlWorkBook = xlApp.Workbooks.Add
        xlWorkSheet = DirectCast(xlWorkBook.Sheets("Sheet1"), Excel.Worksheet)

        xlApp.Visible = False 'Don't show Excel; we can and we don't have too

        xlWorkSheet.Cells(1, 1) = TextBox1.Text
        xlWorkBook.SaveAs("C:\Temp\Book1.xlsx", FileFormat:=56) 'Save the workbook
        xlWorkBook.Close() 'Close workbook
        xlApp.Quit() 'Quit the application

        'Release all of our excel objects we used...
        ReleaseObject(xlWorkSheet)
        ReleaseObject(xlWorkBook)
        ReleaseObject(xlApp)

    Catch ex As Exception
    End Try
End Sub
Public Shared Sub ReleaseObject(ByVal obj As Object)
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub
End Class

请帮忙!

0 个答案:

没有答案