0

我想制作一个程序,使用循环将文本框中的文本保存到 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
4

1 回答 1

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"

当前行 += 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

下一个

当前行 += 1

xlWorkSheet.SaveAs(FileName)

Excel.quit()
Excel = Nothing

我不知道这是否有效,但这是让你开始的东西。

于 2013-03-08T16:56:14.440 回答