如何将文本框文本插入现有的Excel文件? vb.net

时间:2013-03-08 16:34:09

标签: vb.net excel

我想创建一个程序,使用循环将文本框中的文本保存到excel文件,因为我想向excel插入多个文本。我找到了代码但它只覆盖了单元格中的数据。我希望程序找到最后一行并将新数据插入下一行。我被困在这里,请有人帮我在vb.net中做到这一点。这是我的代码:

    Excel = CreateObject("Excel.Application")
    Excel.screenupdating = True
    Excel.Visible = True

    'fieldnames
    Dim xlWorkSheet As Object = Excel.workbooks.add
    Excel.workbooks(1).worksheets(1).cells(1, 1).value = "TITLE"
    Excel.workbooks(1).worksheets(1).cells(1, 2).value = "AUTHOR"
    Excel.workbooks(1).worksheets(1).cells(1, 3).value = "EDITION"
    Excel.workbooks(1).worksheets(1).cells(1, 4).value = "PUBLISHER"
    Excel.workbooks(1).worksheets(1).cells(1, 5).value = "ISBN"

    'i want to loop here the data in textboxes
    Excel.workbooks(1).worksheets(1).cells(2, 1).value = txtTitle.Text
    Excel.workbooks(1).worksheets(1).cells(2, 2).value = txtAuthor.Text
    Excel.workbooks(1).worksheets(1).cells(2, 3).value = txtEdition.Text
    Excel.workbooks(1).worksheets(1).cells(2, 4).value = txtPublisher.Text
    Excel.workbooks(1).worksheets(1).cells(2, 5).value = txtISBN.Text

    xlWorkSheet.SaveAs(FileName)

    Excel.quit()
    Excel = Nothing

1 个答案:

答案 0 :(得分:0)

您需要动态设置rowindex和aplha列的值。 所以像这样

dim currRow as integer = 0
Excel = CreateObject("Excel.Application")
Excel.screenupdating = True
Excel.Visible = True

'fieldnames
Dim xlWorkSheet As Object = Excel.workbooks.add
Excel.workbooks(1).worksheets(1).cells((currRow+1), 1).value = "TITLE"
Excel.workbooks(1).worksheets(1).cells((currRow+1), 2).value = "AUTHOR"
Excel.workbooks(1).worksheets(1).cells((currRow+1), 3).value = "EDITION"
Excel.workbooks(1).worksheets(1).cells((currRow+1), 4).value = "PUBLISHER"
Excel.workbooks(1).worksheets(1).cells((currRow+1), 5).value = "ISBN"

currRow + = 1

表示i为整数= currRow为5

'i want to loop here the data in textboxes
Excel.workbooks(1).worksheets(1).cells((currRow + i), 1).value = txtTitle.Text
Excel.workbooks(1).worksheets(1).cells((currRow + i), 2).value = txtAuthor.Text
Excel.workbooks(1).worksheets(1).cells((currRow + i), 3).value = txtEdition.Text
Excel.workbooks(1).worksheets(1).cells((currRow + i), 4).value = txtPublisher.Text
Excel.workbooks(1).worksheets(1).cells((currRow + i), 5).value = txtISBN.Text

currRow + = 1

xlWorkSheet.SaveAs(FileName)

Excel.quit()
Excel = Nothing

我不知道这是否有效,但这可以帮助你入门。