从DgView导出到Excel时出错

时间:2016-04-14 05:43:19

标签: vb.net excel datagridview

我正在尝试从DataGridView导出到Excel,但如果我在系统要求替换现有文档时选择“否”或“取消”,则该程序会抛出以下错误:

**System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2146827284
HResult=-2146827284
Message=Exception from HRESULT: 0x800A03EC
Source=Consulta Serial
StackTrace:
at Microsoft.Office.Interop.Excel._Worksheet.SaveAs(String Filename, Object FileFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, Object AddToMru, Object TextCodepage, Object TextVisualLayout, Object Local)
at Consulta_Serial.BuscaPorSerial.Export_Button_Click(Object sender, EventArgs e) in C:\Users\jimenu\Documents\Visual Studio 2015\Projects\BETAS\SIBA\Consulta Serial\BuscaPorSerial.vb:line 128**

我使用的代码是:

Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Export_Button.Click
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim misValue As Object = Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer

    xlApp = New Excel.Application
    xlWorkBook = xlApp.Workbooks.Add(misValue)
    xlWorkSheet = xlWorkBook.Sheets("sheet1")


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

    xlWorkSheet.SaveAs("C:\ReportePorSerial.xlsx")
    xlWorkBook.Close()
    xlApp.Quit()

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

    MsgBox("El archivo se genero en la siguiente ruta C:\ReportePorSerial.xlsx")
End Sub


Private Sub releaseObject(ByVal obj As Object)
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

这里的Ulises是一种简单的替代方法,我希望您会感兴趣:

Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Export_Button.Click
    Dim ef = New ExcelFile()
    Dim ws = ef.Worksheets.Add("Sheet1")

    ' From DataGridView to ExcelFile.
    DataGridViewConverter.ImportFromDataGridView(ws, Me.GridGeneral,
        New ImportFromDataGridViewOptions() With {.ColumnHeaders = True})

    ef.Save("C:\ReportePorSerial.xlsx")
End Sub

代码使用GemBox.Spreadsheethere您也可以找到完整的样本。