Vb.net 创建Excel文件时出错

Vb.net 创建Excel文件时出错,vb.net,excel,Vb.net,Excel,我使用vb.net创建excel文件,但它给我一个错误,它无法打开文件,因为文件格式或文件扩展名文件无效 Dim excelLocation As String = txtLocate.Text + txtFilename.Text.Trim + ".xlsx" Dim source1 As New BindingSource Dim APP As New Excel.Application Dim worksheet As Excel.Worksheet

我使用vb.net创建excel文件,但它给我一个错误,它无法打开文件,因为文件格式或文件扩展名文件无效

    Dim excelLocation As String = txtLocate.Text + txtFilename.Text.Trim + ".xlsx"
    Dim source1 As New BindingSource
    Dim APP As New Excel.Application
    Dim worksheet As Excel.Worksheet
    Dim workbook As Excel.Workbook


    If System.IO.File.Exists(excelLocation) = False Then
        System.IO.File.Create(excelLocation).Dispose()
    End If


    workbook = APP.Workbooks.Open(excelLocation)
    worksheet = workbook.Worksheets("sheet1")
    Dim columnsCount As Integer = dgvList.Columns.Count
    For Each column In dgvList.Columns
        worksheet.Cells(1, column.Index + 1).Value = column.Name
    Next

    For i As Integer = 0 To dgvList.Rows.Count - 1
        Dim columnIndex As Integer = 0
        Do Until columnIndex = columnsCount
            worksheet.Cells(i + 2, columnIndex + 1).Value = dgvList.Item(columnIndex, i).Value.ToString
            columnIndex += 1
        Loop
    Next
    workbook.SaveAs()
    workbook.Close()
    MsgBox("Save!")

我相信您正在寻找
.Save
方法。您还应该使用
封送.FinalReleaseComObject
来处理excel对象。我如何在代码中实现这一点@一天,调用
App后,
marshall.FinalReleaseComObject
将在最后运行。对于每个excel对象工作表、工作簿,然后是App,退出