I'm doing an export in VB. I was able to export the values of the datagridview to excel but when I open the file, it shows this error.
I'm using the following code to export the values of the 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
NOTE This code works fine. It exports the values without any problem. It just shows the error when I open the excel file. The exported file has no problem when I click "Yes". It shows the correct values. I just want this error to stop showing when I open the file.
Can anyone help me fix this solution? I will be truly grateful to anyone who can lead me. Thanks. :)
I figured it out. Thanks to akhil kumar.
My Excel uses .xlsx extension so I changed
dlgSave.DefaultExt = "xls"
to
dlgSave.DefaultExt = "xlsx"
and removed the Replace function to make it look like this.
Dim sFileName As String = dlgSave.FileName
This works perfectly. This problem was sorted. :)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments