从 datagridview 导出的 excel 文件在打开时显示错误 VB

Exported excel file from datagridview shows error when opened VB

我正在 VB 中进行导出。我能够将 datagridview 的值导出到 excel,但是当我打开文件时,它显示此错误。

我正在使用以下代码导出 datagridview 的值。

Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim sPath As String = String.Empty
    Dim dlgSave As New SaveFileDialog
    Dim i As Integer
    Dim j As Integer

    dlgSave.DefaultExt = "xls"
    dlgSave.Filter = "Microsoft Excel|*.xls"

    If dlgSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
        xlApp = New Microsoft.Office.Interop.Excel.Application
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")


        For i = 0 To dgvFile.RowCount - 1
            For j = 0 To dgvFile.ColumnCount - 1
                For k As Integer = 1 To dgvFile.Columns.Count
                    xlWorkSheet.Cells(1, k) = dgvFile.Columns(k - 1).HeaderText
                    xlWorkSheet.Cells(i + 2, j + 1) = dgvFile(j, i).Value.ToString()
                Next
            Next
        Next

        Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", ".xlx")

        xlWorkSheet.SaveAs(sFilename)
        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        Dim res As MsgBoxResult
        res = MsgBox("Process completed, Would you like to open file?", MsgBoxStyle.YesNo)
        If (res = MsgBoxResult.Yes) Then
            Process.Start(sFileName)
        End If
    End If

注意 此代码工作正常。它可以毫无问题地导出值。它只是在我打开 excel 文件时显示错误。 点击"Yes"导出的文件没有问题。它显示正确的值。我只想在打开文件时停止显示此错误。

谁能帮我解决这个问题?我将真诚地感谢任何能带领我的人。谢谢。 :)

我明白了。感谢 akhil kumar。

我的 Excel 使用 .xlsx 扩展名,所以我更改了

dlgSave.DefaultExt = "xls"

dlgSave.DefaultExt = "xlsx"

并删除了替换功能,使其看起来像这样。

Dim sFileName As String = dlgSave.FileName

这非常有效。这个问题已经解决了。 :)